How can I store a result in a Matrix?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ben Champion

    #1

    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
  • Steven Bethard

    #2
    Re: How can I store a result in a Matrix?

    Ben Champion wrote:[color=blue]
    > 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:[/color]
    [snip matlab code][color=blue]
    >
    > This gives me the variable y with values
    > 2 3 5 8 13 21 34 55 89 144[/color]

    If you really want to be dealing with matrices, you should probably
    dowload the numarray package:
    The Space Telescope Science Institute helps humanity explore the universe with advanced space telescopes and ever-growing data archives.


    If a list is sufficient, I would write this something like:
    [color=blue][color=green][color=darkred]
    >>> def fib():[/color][/color][/color]
    .... a, b = 1, 1
    .... while True:
    .... yield a
    .... a, b = b, a + b
    ....[color=blue][color=green][color=darkred]
    >>> import itertools as it
    >>> list(it.islice( fib(), 2, 12))[/color][/color][/color]
    [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.islic e 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

    Comment

    Working...