Change the order of matrix

19 visualizzazioni (ultimi 30 giorni)
NA
NA il 1 Apr 2020
Modificato: NA il 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 Commenti
Guillaume
Guillaume il 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 il 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.

Accedi per commentare.

Risposta accettata

Ameer Hamza
Ameer Hamza il 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 Commenti
Ameer Hamza
Ameer Hamza il 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 il 2 Apr 2020
Thanks.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by