Why does my vector repeat numbers?
Mostrar comentarios más antiguos
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
Chad Greene
el 28 de Abr. de 2015
Whoa, careful writing a function called sort. That's already the name of a built-in function! This will make it hard to be confident that Matlab is choosing to use the version of sort that you want Matlab to use. If you use someone else's code or download File Exchange submissions that use the built-in sort, Matlab might try to use your sort instead. Rename your sort to mysort or something meaningful.
CalamityGoat
el 28 de Abr. de 2015
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
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.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Shifting and Sorting Matrices en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!