How to interchange entries of a n array?

2 visualizzazioni (ultimi 30 giorni)
X = [ 4 2 3 6 5 1 ];
x1 = [2 3 1 2];
The following code integange entries of X based on x1
Xnew = X ;
for ii = 1:numel(x1 )
Xnew([ii x1(ii)]) = Xnew([x1(ii) ii ]);
end
Xnew
1- Is there any other faster way to do that?

Risposta accettata

Walter Roberson
Walter Roberson il 28 Mar 2022
Modificato: Walter Roberson il 29 Mar 2022
1- Is there any other faster way to do that?
There are potentially overlaps: a row might get moved in and moved out again. Therefore the changes must be applied in sequence. The only real improvement would be to calculate the full interchange table first, and then shuffle the rows only once.
Mathematically it could be modeled by a series of permutation matrices, like
[1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1]
that all got multiplied together to build the final matrix. If you had a number of different X matrices all to be reordered according to the same pattern it just might be worth building that kind of permutation matrix, but it isn't worth it for one X.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by