471,073 Members | 1,394 Online

# 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
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.