Python – Unable to reproduce numpy-style indexes in MATLAB

Unable to reproduce numpy-style indexes in MATLAB… here is a solution to the problem.

Unable to reproduce numpy-style indexes in MATLAB

This is the Python code I tried to reproduce in MATLAB.

>>> M = np.zeros((5,5))
>>> indices = np.arange(5)
>>> M[indices[:-1], indices[:-1]+1] = 1
>>> print(M)
[[0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0.]]

This is what happened when I wrote in MATLAB.

>> M = zeros(5);
>> indices = 1:5;
>> M(indices(1:end-1), indices(1:end-1)+1) = 1
>>
M =

0     1     1     1     1
     0     1     1     1     1
     0     1     1     1     1
     0     1     1     1     1
     0     0     0     0     0

How can I achieve the same indexing effect in MATLAB?

Solution

MATLAB two-dimensional indexes extract a rectangular submatrix whose rows and columns are reordered according to the provided index vector. But if you have a list of rows and columns and want to extract the corresponding elements, you should convert the two-dimensional index to a linear index, you can use sub2ind. :

M = zeros(5);
indices = 1:5;
idx = sub2ind([5,5],indices(1:end-1), indices(1:end-1)+1);
M(idx) = 1

Or you can use a linear index directly:

M = zeros(5);
M(5+1:5+1:end) = 1

How does linear indexing work?
In MATLAB, data is stored in the column-primary format:

1    6   11   16   21
2    7   12   17   22
3    8   13   18   23
4    9   14   19   24
5   10   15   20   25

When you use the range 6:6

:end, it means that you want to extract elements starting at step 6 of the form element 6, so you need element [6 12 18 24 ]. This indexing scheme can be extended to ND arrays and non-square matrices.

Related Problems and Solutions