How to interchange entries of a n array?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Noor Fatima
el 28 de Mzo. de 2022
Editada: Walter Roberson
el 29 de Mzo. de 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?
0 comentarios
Respuesta aceptada
Walter Roberson
el 28 de Mzo. de 2022
Editada: Walter Roberson
el 29 de Mzo. de 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.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!