MATLAB to Python Conversion, matrices and lists

Question:

How would I translate the following into Python from Matlab? I’m still trying to wrap my head around lists/matrices and arrays in numpy, etc.

outframe(:,[4:4:nout-1]) = 0.25*inframe(:,[1:n-1]) + 0.75*inframe(:,[2:n])
pos=(beamnum>0)*(beamnum<=nbeams)*(binnum>0)*(binnum<=nbins)*((beamnum-1)*nbins+binnum)
for index =1:512:
outarray(index,:) =uint8(interp1([1:n],inarray64(index,:),[1:.25:n],method))

(There’s other stuff, these are just the particular statements I’m not sure how to make sense of. I have numpy imported,

Asked By: Victoria Price

||

Answers:

Let’s try this line by line:

outframe(:,[4:4:nout-1]) = 0.25*inframe(:,[1:n-1]) + 0.75*inframe(:,[2:n])

would translate in “English” to: all rows of outframe, but only every 4th column starting from 4 to nout-1 (i.e.4,8..). I assume you understand what inframe references mean.

pos=(beamnum>0)*(beamnum<=nbeams)*(binnum>0)*(binnum<=nbins)*((beamnum-1)*nbins+binnum)

Possibly beamnum is a vector and (beamnum >0) returns a vector of {0,1} such that the elements are ‘1’ where the respective beamnum element is >0, else 0. The rest of it is clear, i hope.

The second last line is a for-loop and the last line should hopefully be clear.

Answered By: user59634

The main workhorse in numpy is the ndarray (or array). It will for the most part replace matlab matrices when you translate code. Like a matlab matrix, the ndarray stores homogeneous data (ie float64) and is optimized for numerical operations.

The numpy matrix is a subclass of the ndarray which can be convenient for some linear algebra intensive applications. Here is more info about the differences between the two.

The python list is more like a matlab cell array (though not exactly the same). It’s one of the basic python data structures, but in scientific applications I find that it comes up most often when you need to hold heterogeneous data. (Or when you’re doing something very simple and don’t want to go to the trouble of creating a numpy array).

Your code above can be converted almost verbatim to python using the ndarray and replacing () with [] for indexing and taking into account that indexing starts at 1 in MATLAB and 0 in python
i.e. : the first element in MATLAB is element 1, and in python it is element 0.

Answered By: Bi Rico
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.