How to interchange position of a matrix?

1 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2022-9-14
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

更多回答(1 个)

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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by