Change the order of matrix
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
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?
Risposta accettata
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
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,:);
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices 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!