MATLAB Answers

Compare two matrices and select max one based on the a column

1 view (last 30 days)
Yaser Khojah
Yaser Khojah on 17 Mar 2020
Commented: Yaser Khojah on 17 Mar 2020
I have two matrixes and I want to compare the last column. Then select the max one and the whole corresponding row.
For example
A = [ 1 , 4, 5; 1, 4, 6];
B = [2, 6, 6; 2, 5 , 9];
The next matrix based on the last column max will be
C = [2, 6, 6; 2, 5 , 9];
Anyway to help, please

  0 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 17 Mar 2020
If I understood correctly:
C = A;
replacebyB = B(:, end) > A(:, end);
C(replacebyB, :) = B(replacebyB, :);
The above gives priority to A when the last columns are equal.

More Answers (1)

madhan ravi
madhan ravi on 17 Mar 2020
C = max(A,B)

  3 Comments

Yaser Khojah
Yaser Khojah on 17 Mar 2020
It does not work in my example. I have to select the max of the last column then select its row? This one would compare element by element
madhan ravi
madhan ravi on 17 Mar 2020
Illustrate the answer if the B were to be
B = [2, 6, 4; 2, 5 , 9];
Yaser Khojah
Yaser Khojah on 17 Mar 2020
Something like this without the forloop
C = zeros(size(A));
for i = 1:11
c = [A(i,:);B(i,:)];
[Max_v, idx] = max(c(:,end));
C(i,:) = c(idx,:);
end

Sign in to comment.

Sign in to answer this question.

Tags


Translated by