Reputation: 42439
I'm converting some Matlab code into Python, and I've found a line I can not understand:
Y = reshape(X(j+(1:a*b),:),[b,a,p])
I know that the reshape
function has a numpy analog and I have read the Matrix Indexing in MATLAB document, but I can't seem to comprehend that line enough to convert it to numpy
indexing/slicing.
I tried the online converter OMPC but it uses functions that are not defined outside of it (like mslice
):
Y = reshape(X(j + (mslice[1:a * b]), mslice[:]), mcat([b, a, p]))
I've also tried the SMOP converter but the result is also hard to understand:
Y = reshape(X(j + (arange(1, dot(a, b))), arange()), concat([b, a, p]))
Could you explain the conversion in simple Matlab to numpy
indexing/slicing rules?
Upvotes: 2
Views: 491
Reputation: 231595
In an Octave session:
>> 1:3*3
ans =
1 2 3 4 5 6 7 8 9
In numpy ipython:
In [8]: np.arange(1,10)
Out[8]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [9]: np.arange(3*3)
Out[9]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
Upvotes: 1
Reputation: 2412
Y = X[j+np.arange(a*b),:].reshape((b,a,p))
Without knowing what you exactly want, this is a translation of the matlab line to python.
Notice that matlab indexes start at 1, while numpy's start at 0. So depending on the other lines the inner line could be either np.arange(a*b)
or np.arange(1,a*b)
.
Also you don't really need to use the second index of X
, so X[1,:]==X[1]
is True
Upvotes: 2