From: Christopher B. <Chr...@no...> - 2006-02-23 17:19:47
|
Albert Strasheim wrote: > There are other (unexpected, for me at least) differences between > MATLAB/Octave and NumPy too. First: numpy is not, and was never intended to be, a MATLAB clone, work-alike, whatever. You should *expect* there to be differences. > For a 3D array in MATLAB, only indexing > on the last dimension yields a 2D array, where NumPy always returns a > 2D array. I think the key here is that MATLAB's core data type is a matrix, which is 2-d. The ability to do 3-d arrays was added later, and it looks like they are still preserving the core matrix concept, so that a 3-d array is not really a 3-d array; it is, as someone on this thread mentioned, a "stack" of matrices. In numpy, the core data type is an n-d array. That means that there is nothing special about 2-d vs 4-d vs whatever, except 0-d (scalars). So a 3-d array is a cube shape, that you might want to pull a 2-d array out of it in any orientation. There's nothing special about which axis you're indexing. For that reason, it's very important that indexing any axis will give you the same rank array. Here's the rule: -- indexing reduces the rank by 1, regardless of which axis is being indexed. >>> import numpy as N >>> a = N.zeros((2,3,4)) >>> a array([[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]) >>> a[0,:,:] array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> a[:,0,:] array([[0, 0, 0, 0], [0, 0, 0, 0]]) >>> a[:,:,0] array([[0, 0, 0], [0, 0, 0]]) -- slicing does not reduce the rank: >>> a[:,0:1,:] array([[[0, 0, 0, 0]], [[0, 0, 0, 0]]]) >>> a[:,0:1,:].shape (2, 1, 4) It's actually very clean, logical, and useful. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chr...@no... |