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

Charles R Harris charlesr.harris at gmail.com
Mon Mar 5 12:04:31 EST 2007


On 3/5/07, David Koch <ogdude at googlemail.com> wrote:
>
> Hello,
>
> I am trying to translate some Matlab code to NumPy. I started reading the
> NumPy book and, yeah it's a very long read :-/ One thing I am completely
> confused about are the concpets of "basic" vs. "advanced" indexing. Are
> there some good examples out there where for the same piece of code - Matlab
> and NumPy are compared? I feel looking at those maybe more helpful to get me
> started than an in-depth study of the book. I already read "Numpy for Matlab
> users" and at a glance it doesn't seem to contain equivalents to all the
> common indexing operations you'd do in Matlab.
>
> Some concrete problems/questions I have right now:
>
> - 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)?


Usually arrays are created from the data with their final dimensions set as
part of the creation. You don't need to define an array and then fill in the
values and it is best to avoid this where possible. Subarrays are best
treated as views that require not copying of data, something that is missing
from Matlab.

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


Look at delete. It is best to avoid such constructions when possible because
they involve a data copy.

- For (basic ?) indexing of an ndarray - is there any reason to prefer
> A[i,j] over A[i][j]?
> - Is it "pythonic" to initialize vectors to 2 dimensions so that vec.shape== (len(vec), 1) instead of
> vec.shape == (len(vec),)?


There are two schools here, those who use matrices so that everything is 2d,
and those who use arrays. One dimensional arrays will work fine for such
things as matrix multiplication, so there is really no need for the second
dimension. In any case, a faster way to implement your example is

vec.reshape(-1,1)

where the -1 fills in the dimension to use all of the array.

matrix(vec)

will return an 1xn matrix

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20070305/b27fe4fb/attachment.html>


More information about the NumPy-Discussion mailing list