Effacer les filtres
Effacer les filtres

How to interchange position of a matrix?

1 vue (au cours des 30 derniers jours)
Ammy
Ammy le 14 Sep 2022
Commenté : Ammy le 14 Sep 2022
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.

Réponse acceptée

Stephen23
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
X = 1×3
3 1 2

Plus de réponses (1)

Torsten
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
X = 1×3
3 1 2
  1 commentaire
Ammy
Ammy le 14 Sep 2022
@Torsten Yes, my interpretation is the same and your answer fulfill that. Thank you very much.

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB 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!

Translated by