Change the order of matrix

조회 수: 12 (최근 30일)
NA
NA 2020년 4월 1일
편집: NA 2020년 4월 2일
I want to change the order of B in accordance with Index.
Index means that 'row 2' in B should change to 'row 5' in New_B.
I wrote this code, but I don't know how to add remain elements in B to New_B.
B = [1 2; 1 4; 1 6; 1 8; 2 3; 2 7; 3 4; 3 6; 3 8; 4 6; 4 7; 6 7; 6 8; 7 8];
Index = [2,5; 4,1; 6,6; 8,2; 9,7; 10,3; 11,9; 12,4; 14,8];
New_B = zeros(size(B));
for i=1:length(Index)
temp = Index(i,:);
if temp(1)~=temp(2)
New_B(temp(2),:) = B(temp(1),:);
end
end
result should be
New_B = [1,8; 3,6; 4,6; 6,7; 1,4; 1,2; 3,8; 7,8; 4,7; 1,6; 2,3; 2,7; 3,4; 3,4; 6,8]
  댓글 수: 3
Guillaume
Guillaume 2020년 4월 1일
Your index matrix tells us what happens to some of the rows of B. What about the others? What should be done about them?
Also, what if the instructions in Index conflict? e.g. Index sends 2 rows to the same destination?
NA
NA 2020년 4월 1일
''Given that the second column of Index only has indices going up to 9, how does your example output New_B contain 15 rows?''
B and New_B should be the same size.
''What about the others? What should be done about them?''
Orders of others are not impotant and coming after the arranged index.
''what if the instructions in Index conflict? e.g. Index sends 2 rows to the same destination?''
I have not encountered with mentioned case yet.

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 4월 1일
Try this:
B = [1 2; 1 4; 1 6; 1 8; 2 3; 2 7; 3 4; 3 6; 3 8; 4 6; 4 7; 6 7; 6 8; 7 8];
Index = [2,5; 4,1; 6,6; 8,2; 9,7; 10,3; 11,9; 12,4; 14,8];
B_temp = B;
B_temp(Index(:,1),:) = [];
B_new(Index(:,2),:) = B(Index(:,1),:);
B_new = [B_new; B_temp];
  댓글 수: 4
Ameer Hamza
Ameer Hamza 2020년 4월 2일
Now the rule is a bit clear. Is this the required result?
B = [1 2; 2 3; 3 4; 4 5; 4 6; 6 8; 7 8];
Index = [3 2; 4 5; 5 7];
idx1 = Index(:,1);
idx2 = Index(:,2);
idx3 = setdiff(1:size(B,1), idx2)';
idx4 = setdiff(1:size(B,1), idx1)';
B_new(idx2, :) = B(idx1,:);
B_new(idx3, :) = B(idx4,:);
NA
NA 2020년 4월 2일
Thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by