matlab indexing and swapping
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
zhi zhu
el 9 de Mzo. de 2017
Editada: James Tursa
el 9 de Mzo. de 2017
x = [6 5 3 5 9 10 438 4 1 4 7 0 4 8 4 2];
len = length(x);
minval = x(1);
for n = 1:len
for i = 1:len
if x(i) < minval
minval = x(i);
end
end
sortval(i) = minval;
x(n find(x==minval)) = x(find(x==minval) n);
x(n) = [];
end
disp(sortval)
I am trying to swap the position of n and my minval so I can delete that minval later and not affect the process of sorting later in the for loop.
0 comentarios
Respuesta aceptada
James Tursa
el 9 de Mzo. de 2017
Editada: James Tursa
el 9 de Mzo. de 2017
This isn't going to work like you hoped. If you delete an element from the array with this line:
x(n) = [];
Then there are no longer len elements in the x array, so this will eventually yield an error because i will be out of bounds for the shortened length of x (i.e., len is no longer the actual length of x):
for i = 1:len
if x(i) < minval
So first thing you need to do is rewrite your code to fix this problem, then we can worry about how to swap elements (if that step still remains in your fixed code).
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices 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!