how to exchange matrix rows depending on distance

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?

 採用された回答

Guillaume
Guillaume 2014 年 11 月 16 日
編集済み: Guillaume 2014 年 11 月 16 日

1 投票

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 件のコメント

janny
janny 2014 年 11 月 16 日
It didn't give the same answer, even the matrix came with shorter rows,i have the code as:
S = pdist(A,'minkowski',1);
S_matrix = squareform(S);
D1 = [0; diag(S_matrix,1)]
C = pdist(B,'minkowski',1);
C_matrix = squareform(C);
D2 = [0; diag(C_matrix,1)]
idx = find(D2 > D1);
A(idx, :) = B(idx, :);
fileID = fopen('outputq1.txt','w')
fprintf(fileID,'%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\r\n',A') fclose(fileID);
the output is not right. check it please. something went wrong.
Guillaume
Guillaume 2014 年 11 月 16 日
I can't test your code, I don't have the stats toolbox (no pdist) and you haven't given A and B.
In any case,
A = [1 2 3 4]'
B = [11 12 13 14]'
D1 = [0 14 15 16]' %as in your example
D2 = [0 16 19 14]' %as in your example
A(D2>D1) = B(D2>D1)
returns
A =
1
12
13
4
which is what you asked.
Whatever problem you're having, it's not to do with my bit of code.
janny
janny 2014 年 11 月 16 日
編集済み: janny 2014 年 11 月 16 日
thank you very much... its working fine now,,,,

サインインしてコメントする。

その他の回答 (1 件)

MA
MA 2014 年 11 月 16 日

1 投票

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 件のコメント

Guillaume
Guillaume 2014 年 11 月 16 日
M.A., Your loop is equivalent to:
idx = A(:,2)<B(:,2);
A(idx, :) = B(idx, :);
No need for a loop.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

質問済み:

2014 年 11 月 16 日

編集済み:

2014 年 11 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by