471,073 Members | 1,394 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,073 software developers and data experts.

How can I store a result in a Matrix?

I am new to Python so please excuse me if this sounds simple! Before I
explain what i want to do let me write some code in matlab which
demonstrates what I would like to acheive, using the Fibonnachi series
as an example:
a = 1
b = 1
for i = 1:10
z = a + b
a = b
b = z
y(i) = z
end

This gives me the variable y with values
2 3 5 8 13 21 34 55 89 144

which is essentially a matrix which i can plot against another matrix
xof the same dimensions

In python I have

a = 1
b = 1
for i in range(1, 11)
z = a + b
a = b
b = z

which gives me all the values I need, but i do not know how to store
the values of z in a single matrix. I have looked at several online
resources and played about with the array commands but cant get it to
work. If someone could point me to a relevant webpage or suggest code
that will work I would be very grateful

Thanks

Ben
Jul 18 '05 #1
1 1452
Ben Champion wrote:
I am new to Python so please excuse me if this sounds simple! Before I
explain what i want to do let me write some code in matlab which
demonstrates what I would like to acheive, using the Fibonnachi series
as an example: [snip matlab code]
This gives me the variable y with values
2 3 5 8 13 21 34 55 89 144


If you really want to be dealing with matrices, you should probably
dowload the numarray package:
http://www.stsci.edu/resources/softw...dware/numarray

If a list is sufficient, I would write this something like:
def fib(): .... a, b = 1, 1
.... while True:
.... yield a
.... a, b = b, a + b
.... import itertools as it
list(it.islice(fib(), 2, 12))

[2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

The fib function is a generator that will yield, one at a time, each
value in the fibonacci sequence. Since you only wanted values 2 through
11 in your example, I use itertools.islice to select the appropriate
part of the generated sequence.

Note also that because Python has tuple unpacking, you can do multiple
simulaneous assignment, so there's no need to have that extra temp
variable 'z'.

Steve
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Michael Allen | last post: by
3 posts views Thread by jacob nikom | last post: by
12 posts views Thread by Sanjay | last post: by
6 posts views Thread by n00dle | last post: by
2 posts views Thread by DarrenWeber | last post: by
reply views Thread by DarrenWeber | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.