How to interchange position of a matrix?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
A = [3 1 2];
B = [2 3 1];
%%%%%
X = [2 1 3];
%%%
I want to interchange position of elements in X using A and B.
=> interchange 3rd element of X with 2nd element => X1 = [2 3 1 ]
=> interchange 1st element of X1 with its 3rd element => X2 = [1 3 2]
=> interchange 2nd element of X2 with its fisrt element => X3 = [ 3 1 2]
only need the last output that is X3.
I have tried the following
X(A) = X(fliplr(A))
But not getting how to use both A and B.
0 commentaires
Réponse acceptée
Stephen23
le 14 Sep 2022
A = [3,1,2];
B = [2,3,1];
X = [2,1,3];
for k = 1:numel(X)
X([A(k),B(k)]) = X([B(k),A(k)]);
end
X
Plus de réponses (1)
Torsten
le 14 Sep 2022
Are you sure that the changes should be performed subsequently with the new vectors obtained from the steps before ?
My guess would be that the 3rd element of X should be replaced by the 2nd element of X, the 1st element of X should be replaced with the 3rd element of X and the 2nd element of X should be replaced with the 1st element of X, resulting in [ 3 2 1].
If your interpretation is correct, use a loop:
A = [3 1 2];
B = [2 3 1];
X = [2 1 3];
for i = 1:numel(X)
tmp = X(A(i));
X(A(i)) = X(B(i));
X(B(i)) = tmp;
end
X
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!