Filter löschen
Filter löschen

How to interchange elements of an array?

1 Ansicht (letzte 30 Tage)
Noor Fatima
Noor Fatima am 27 Mär. 2022
Kommentiert: Voss am 28 Mär. 2022
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.

Akzeptierte Antwort

Voss
Voss am 27 Mär. 2022
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 Kommentare
Noor Fatima
Noor Fatima am 28 Mär. 2022
@_Thank you, Is it possible without loop?
Voss
Voss am 28 Mär. 2022
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements 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