Filter löschen
Filter löschen

How to interchange position of a matrix?

1 Ansicht (letzte 30 Tage)
Ammy
Ammy am 14 Sep. 2022
Kommentiert: Ammy am 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.

Akzeptierte Antwort

Stephen23
Stephen23 am 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

Weitere Antworten (1)

Torsten
Torsten am 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 Kommentar
Ammy
Ammy am 14 Sep. 2022
@Torsten Yes, my interpretation is the same and your answer fulfill that. Thank you very much.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by