Why does my vector repeat numbers?

2 visualizaciones (últimos 30 días)
CalamityGoat
CalamityGoat el 28 de Abr. de 2015
Comentada: Chad Greene el 28 de Abr. de 2015
So I am trying to sort a random array of integers and with my code everything works except certain numbers will repeat multiple times. I'm not sure what I am doing that's making it repeat but I think it has to do with me possibly overwriting my variable x(k).
function y = sort(x)
for k = 1:length(x)-1
% Compare x(k) with values in original array x
for i = (k+1):length(x)
if x(k) < x(i)
temp = 0;
temp = x(i);
x(k) = temp;
end
end
y = x;
  4 comentarios
Stephen23
Stephen23 el 28 de Abr. de 2015
Also note that you should avoid using i and j as variable names, as these are both names of the inbuilt imaginary unit.
Chad Greene
Chad Greene el 28 de Abr. de 2015
Also be careful using i and j as variables. They're both built in as the imaginary unit. Overwriting them is usually not a problem, but when it is a problem, it can be hard to track down.

Iniciar sesión para comentar.

Respuesta aceptada

KL
KL el 28 de Abr. de 2015
Editada: KL el 28 de Abr. de 2015
for j = 1:length(x)-1
% Find jth smallest element
imin = j;
for i = (j + 1):length(x)
if (x(i) < x(imin))
imin = i;
end
end
if (imin ~= j)
val = x(imin);
x(imin) = x(j);
x(j) = val;
end
end
  1 comentario
CalamityGoat
CalamityGoat el 28 de Abr. de 2015
Works perfectly had to change the logical expression so the array would descend rather than ascend. Thanks a bunch.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by