[Numpy-discussion] Matlab -> NumPy translation and indexing

Sturla Molden sturla@molden...
Mon Mar 5 08:24:15 CST 2007


On 3/5/2007 2:13 PM, David Koch wrote:

> - Am I correct in assuming that all arrays have to be initialized to 
> their final number of elements in NumPy (using empty/zero for instance)?

You can also create an array from a Python list, data in a file, another 
array or a memory mapping. In these cases you don't need to know the 
size of the array in advance.

But once created you cannot append elements to a NumPy array as you can 
with a Python list. NumPy arrays never call realloc due to the 
complication from view arrays.


> - Given a matrix R, is there an equvialent to the Matlab operation 
> R(:,j) = [] (which removes column j and "shrinks" the matrix?

Matlab does not have view arrays and no regard for memory consumption or 
fragmentation, so it can make a copy behind the scenes. In NumPy you 
have to be more explicit about what is done.

def remove_column(a,j):
    idx = arange(0,a.shape[1])
    idx = idx[idx != j]
    return a[:,idx]


> - For (basic ?) indexing of an ndarray - is there any reason to prefer 
> A[i,j] over A[i][j]?

The latter involves two function calls and creation of an intermediate 
object (a view array).


> - Is it "pythonic" to initialize vectors to 2 dimensions so that 
> vec.shape == (len(vec), 1) instead of vec.shape == (len(vec),)?

I have no idea.


S.M.





More information about the Numpy-discussion mailing list