PDA

View Full Version : Matrix in python


krypto_wizard
February 8th, 2006, 11:36 PM
I programmed pretty much in C all my life. Now I am learning python.

I have a very basic question. In C you define and have array like


int[] a = {1,2,3,4,5}

or int[2][2] a = { {2,3},
{3,2},
}

The above code show matrix like this
2 3
3 2

How do u do it in python. I understand list, but how do u use those lists to make 2D and 3D array in Python.

I think I am not able to think beyond C, which I think needs to be changed.

All your help is appreciated.

Thanks

cwaldbieser
February 9th, 2006, 12:36 AM
I programmed pretty much in C all my life. Now I am learning python.

I have a very basic question. In C you define and have array like


int[] a = {1,2,3,4,5}

or int[2][2] a = { {2,3},
{3,2},
}

The above code show matrix like this
2 3
3 2

How do u do it in python. I understand list, but how do u use those lists to make 2D and 3D array in Python.

I think I am not able to think beyond C, which I think needs to be changed.

All your help is appreciated.

Thanks

A simple matrix of nested lists:

>>> x = [ [1,2,3],
[4,5,6],
[7,8,9]]
>>> x[0][0]
1
>>> x[1][1]
5

celloandy
February 9th, 2006, 07:29 PM
Native Python arrays are slow for matrix operations, so if you plan to do actual matrix operations (in the linear algebra sense), take a look at NumArray (http://www.stsci.edu/resources/software_hardware/numarray). It's much faster for that sort of thing.

Andrew

krypto_wizard
February 10th, 2006, 12:39 AM
thanks, I will take a look at it.


Native Python arrays are slow for matrix operations, so if you plan to do actual matrix operations (in the linear algebra sense), take a look at NumArray (http://www.stsci.edu/resources/software_hardware/numarray). It's much faster for that sort of thing.

Andrew