How to interchange elements of an array?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Noor Fatima
el 27 de Mzo. de 2022
Comentada: Voss
el 28 de Mzo. de 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.
0 comentarios
Respuesta aceptada
Voss
el 27 de Mzo. de 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
2 comentarios
Voss
el 28 de Mzo. de 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])
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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Introduction to Installation and Licensing 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!