[Numpy-discussion] Using 2-D arrays in Numeric Python (numpy)

Chris.Barker Chris.Barker@noaa....
Mon Oct 13 11:35:49 CDT 2008


Linda Seltzer wrote:
> I would appreciate it if someone could answer my question without
> referring to subjects such as APIs and interfaces, since I am only
> concerned with a mathematical application at this time.

caution: this is a bit rude -- that was an excellent and informative 
answer to your not-very-clear question.

No matter how you slice it, you're going to need to learn a bit about 
computer programming in general, and python in particular, in order to 
be productive with numpy.

> I wish that tutorials provided real world examples.

They certainly do -- just not the one you happen to be looking for. It's 
not good form to criticize folks work that they have generously donated.

> I would appreciate it if someone could give me the actual statements
> needed to define and initialize a 2-D array of size NxN, where N can be
> any large number,

There are a few ways to initialize numpy arrays:

import numpy as np

a = np.zeros((M,N))
a = np.ones ((M,N))
a = np.empty((M,N), dtype=np.float)

> In Matlab, this is done as a = zeros(256,256).

If you are familiar with Matlab, you'll want to take a look at the Wiki 
pages that describe the similarities and differences between numpy and 
Matlab:

http://www.scipy.org/NumPy_for_Matlab_Users

numpy is more complex, but also more powerful than Matlab -- it will 
take a bit of learning, but it's worth it.

Also, read some of the intros to python itself -- you'll need to 
understand importing and name spaces.

a couple quick examples:

1) numpy has many different data types. In the examples above, you will 
get double precision floats by default (like Matlab), but you can also 
get other data types (with your image examples, you'll want that). For 
example, one way to store an RBG image:

a = np.zeros((w,h,3), dtype=np.uint8)

that is, a width x height x 3 array of 8bit unsigned integers.

2) arrays and matrices are different.

3) numpy provides n-d matrices, not just 2-d

4) importing and name spaces.

>  If I try this in python,
> it won't let the program overwrite the zeros.

if something doesn't work as expected, always post your code, exactly as 
you tested it, so we can tell you what's wrong.

Also, post specific questions -- you first question was something like 
"can I work with arrays", which is quite different than this one: "how 
do I create an array of nXn size full of zeros?"

-Chris

-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker@noaa.gov


More information about the Numpy-discussion mailing list