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

Chad Greene
Chad Greene 2015년 4월 28일
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
CalamityGoat 2015년 4월 28일
Thanks for looking out when I copy pasted my code I realized I didn't get my function line so I just named it something generic for my post hence "sort".
Stephen23
Stephen23 2015년 4월 28일
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 2015년 4월 28일
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.

댓글을 달려면 로그인하십시오.

 채택된 답변

KL
KL 2015년 4월 28일
편집: KL 2015년 4월 28일

0 개 추천

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

CalamityGoat
CalamityGoat 2015년 4월 28일
Works perfectly had to change the logical expression so the array would descend rather than ascend. Thanks a bunch.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

태그

질문:

2015년 4월 28일

댓글:

2015년 4월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by