Skip to content
Advertisement

Translate Matlab’s vector assignment into Python form

I’m trying to translate some Matlab code into Python (using NumPy). I’m not very familiar with Matlab, and I’ve encountered a line that I’m having trouble parsing:

w(idx(1:p, 1), 1) = v(idx(1:p, 1), 1) - theta;

I’d hazard a guess that a p-long head of x is being used as indices to select p entries of w, and that those entries in w are being replaced by corresponding entries in v (less a scalar theta).

Messing around in Octave, that seems like an accurate description of what it’s doing, but I can’t find any documentation to that effect.

In any case, what’s the best way to re-write this code in Python? I’ve looked at the NumPy ‘Tentative Tutorial’ to try and find an elegant way to do it, and it looks like this might be what I’m looking for. However, I’m having trouble making it look nice, particularly with the assignment operator. Are there any more elegant or Python-idiomatic ways to do this assignment operation?

Advertisement

Answer

This is basically what @Dan wrote in the comments, but accounts for zero-based indexing in python:

w[idx[:p, 0], 0] = v[idx[:p, 0], 0] - theta

Not sure if you wanted something more elegant than that. Those zeros are required if only the first column should be modified.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement