How to interchange elements of an array?

조회 수: 2 (최근 30일)
Noor Fatima
Noor Fatima 2022년 3월 27일
댓글: Voss 2022년 3월 28일
X = [ 4 2 3 6 5 1]
x1 = [2 3 1 2]
I want to interchange entries of X based on x1, that is
Output X =[4 6 2 3 5 1];
Any help is appreciated.

채택된 답변

Voss
Voss 2022년 3월 27일
X = [ 4 2 3 6 5 1];
x1 = [2 3 1 2];
Xnew = X;
for ii = 1:numel(x1)
Xnew([ii x1(ii)]) = Xnew([x1(ii) ii]);
end
Xnew
Xnew = 1×6
4 6 2 3 5 1
  댓글 수: 2
Noor Fatima
Noor Fatima 2022년 3월 28일
@_Thank you, Is it possible without loop?
Voss
Voss 2022년 3월 28일
Well, you can write down an expression to do it in this particular case:
X = [ 4 2 3 6 5 1];
Xnew = X([1 4 2 3 5 6])
Xnew = 1×6
4 6 2 3 5 1
But I don't think you can do it in general without using a loop somewhere, because the result of any swap depends on the results of the previous swaps, so it's necessarily an iterative process.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by