how to exchange matrix rows depending on distance

1 view (last 30 days)
hi guys, i have the following matrix A with distance D1 and matrix B with distance D2.
i want a code to exchange A rows with B rows which have higher distance, as moving row 2 in B to matrix A row 2 and remove the old row 2 in A. the output should be:
how to do this guys?

Accepted Answer

Guillaume
Guillaume on 16 Nov 2014
Edited: Guillaume on 16 Nov 2014
Hum, I'm sure I've seen a very similar question (same illustration) in the past. Is this homework?
find the index of the rows you want to exchange:
idx = find(D2 > D1);
And use that to copy the rows of B in A:
A(idx, :) = B(idx, :);
Or, using logical indexing:
A(D2>D1, :) = B(D2>D1);
  3 Comments
janny
janny on 16 Nov 2014
Edited: janny on 16 Nov 2014
thank you very much... its working fine now,,,,

Sign in to comment.

More Answers (1)

MA
MA on 16 Nov 2014
clear all
close all
clc;
A=[11 22 33 44;0 14 15 16]'
B=[66 77 88 99;0 16 19 14]'
for i=1:4
if A(i,2)<B(i,2)
A(i,1)=B(i,1);
end
end
A
  1 Comment
Guillaume
Guillaume on 16 Nov 2014
M.A., Your loop is equivalent to:
idx = A(:,2)<B(:,2);
A(idx, :) = B(idx, :);
No need for a loop.

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!