Reputation: 23
I have 2 matrices A
and B
.
I find the max values in the columns of A, and keep their indices in I. So far so good. Now, I need to choose those arrays of B with the same index as stored in I. I don't know how to do this. See below:
A = [1,2,3; 0,8,9]
B = [0,1,2; 4,2,3]
[~,I] = max(A)
h = B(I)
I need to get these values of B
:
h = [0 2 3]
But the code results in a different one. How can I fix it?
A =
1 2 3
0 8 9
B =
0 1 2
4 2 3
I =
1 2 2
h =
0 4 4
Thanks in advance
Upvotes: 2
Views: 349
Reputation: 25232
The max
function how you used it works like
If A is a matrix, then
max(A)
is a row vector containing the maximum value of each column.
so M = max(A)
is equivalent to M = max(A,[],1)
. But rather use the third input if you're not sure.
If you use max
to find the maxima in the columns of the matrix, it returns the row indices. The column indices are for your case simply 1:size(A,2) = [1 2 3]
.
Now you need to convert your row and column indices to linear indices with sub2ind
:
%// data
A = [1,2,3; 0,8,9]
B = [0,1,2; 4,2,3]
%// find maxima of each column in A
[~, I] = max( A, [], 1 ) %// returns row indices
%// get linear indices for both, row indices and column indices
I = sub2ind( size(A), I, 1:size(A,2) )
%// index B
h = B(I)
returns:
h =
0 2 3
Upvotes: 2