How can I store a result in a Matrix?

B

Ben Champion

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
 
S

Steven Bethard

Ben said:
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/software_hardware/numarray

If a list is sufficient, I would write this something like:
.... a, b = 1, 1
.... while True:
.... yield a
.... a, b = b, a + b
.... [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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,434
Messages
2,571,690
Members
48,796
Latest member
Greg L.

Latest Threads

Top