Effacer les filtres
Effacer les filtres

How to interchange entries of a n array?

2 vues (au cours des 30 derniers jours)
Noor Fatima
Noor Fatima le 28 Mar 2022
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?

Réponse acceptée

Walter Roberson
Walter Roberson le 28 Mar 2022
Modifié(e) : Walter Roberson le 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.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by