Change the order of matrix

19 次查看(过去 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,:);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by