필터 지우기
필터 지우기

How to interchange position of a matrix?

조회 수: 1 (최근 30일)
Ammy
Ammy 2022년 9월 14일
댓글: Ammy 2022년 9월 14일
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