Clear Filters
Clear Filters

Change the order of matrix

8 views (last 30 days)
NA
NA on 1 Apr 2020
Edited: NA on 2 Apr 2020
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 Comments
Guillaume
Guillaume on 1 Apr 2020
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 on 1 Apr 2020
''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.

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 1 Apr 2020
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 Comments
Ameer Hamza
Ameer Hamza on 2 Apr 2020
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 on 2 Apr 2020
Thanks.

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!