2
votes

I am a newbie in python and got python-code to translate into Matlab for my work. I have a specific problem:

I've got a matrix with size for example (rows/columns/3rd dim) = (3/4/2).

A = array([[[1, 56, 0, 6],[5, 9, 10, 3],[50, 51, 59, 64]],[[2, 6, 4, 3],[10, 80, 53, 6],[12, 5, 36, 15]]])

For this matrix (and others) I have given the function

B = A.argmin(axis=-1)

which searches for the index of the minimum in every row. (numpy.argmin Manual)

B is in this case:

B = array([[2, 3, 0],[0, 3, 1]])

and of size (rows/columns) = (2/3).

My ame is to convert exactly this into a Matlab-version, so that I get exactly this matrix, but in Matlab ([Min Matlab Manual][2])

[~,B] = min(A,[],2)

gives me a matrix of size (row/colums/3rd dim) = (3/1/2). Matlab Output

The indices of the minimum in each row are the same, if one regard that python starts indexing at 0 and matlab at 1. The problem is the order of the matrix.

How do I get the indeces of the minimum of each row in exact the order as python does it in matlab?

I tried a lot with permute and vertcat, but this didn't work out and in the end it has to work for really big matrices.

I would be pleased, if someone could help me. Thanks in advance!

1
Welcome to Stack Overflow! Please explain a bit more clearly how the results differ. Also, please consider adding the outputs as code instead of pictures.Andras Deak

1 Answers

5
votes

The only problem is that you're taking the wrong dimension in MATLAB. The axis=-1 in numpy corresponds to the last dimension (so I don't think it looks along each row as you've stated in the question), i.e. min(A,[],3):

A(1,:,:)=[1 56 0 6; 5 9 10 3; 50 51 59 64];
A(2,:,:)=[2 6 4 3; 10, 80, 53,  6; 12,  5, 36, 15];
[~,B] = min(A,[],3);

Resulting in:

B =

     3     4     1
     1     4     2

Which, as you said, corresponds to the numpy index matrix

In [409]: B = A.argmin(axis=-1)

In [410]: B
Out[410]: 
array([[2, 3, 0],
       [0, 3, 1]])

Note that if you'd have used min(A,[],2) in MATLAB, the resulting matrix would've been of size [2,1,4]. To get rid of the singleton dimension, you would've had to use squeeze(B) to get a 2d array.

Also note that you might have messed up your original matrix. Your numpy ndarray is of shape (2,3,4), this is the reason why I created the MATLAB counterpart by assigning 3x4 matrices to A(1,:,:) and A(2,:,:). I find this a likely source of confusion, since you claim to have ended up with a matrix of size [2,1,3] (and not [2,1,4]), but then your last two dimensions must have been switched in MATLAB.