self made sorting numbers function

조회 수: 6 (최근 30일)
zhi zhu
zhi zhu 2017년 3월 6일
댓글: Cameron Stark 2017년 9월 16일
I am trying to write my own sort function.. it gave me an error idk how to fix.
for j = 1:length(x)
for i = 1:length(x)-1
if x(i) < x(i+1)
minval = x(i);
val = x(i);
x(i) = [];
end
end
sortval(j) = val;
end
fprintf(sortval);
  댓글 수: 2
Rik
Rik 2017년 3월 6일
If you want to do this, you should at the very least loop backwards through your vector. You are removing elements, so at some point x will no longer have the length that your for-loops expect.
Cameron Stark
Cameron Stark 2017년 9월 16일
function b=downsort(b)
i=.5;
n = length(b);
while i<1
for x =1:n
if x ==n
i = 2;
break
end
if b(x) < b(x+1)
a = b(x);
b(x) = b(x+1);
b(x+1) = a;
break
end
end

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

채택된 답변

Walter Roberson
Walter Roberson 2017년 3월 6일
What is the point of assigning the same value to both minval and val ?
What is the point of assigning to minval when you never use minval again?
Note:
You are deleting elements from an array using a forward-indexing "for" loop. Suppose you have 4 elements and you delete the 2nd one in the loop:
i = 2, x = [A B C D], x(i) = []
now x = [A C D] because x(2) was deleted.
Now proceed to i = 3 in your for loop, and look at x(i). That is looking at D -- what happened to looking at C ?
When you delete something from vector, all the later elements "fall down" to fill the hole, getting renumbered along the way. If you increase the loop counter then you skip over the entry that fell down into the place you just looked.
You can deal with this in one of a few ways:
  1. avoid deleting elements at all (for example, copy elements into a different array instead of deleting them out of the existing array); or
  2. keep track of what is to be deleted but do not deleted it while you are looping; instead, at the end delete all of the ones you marked for deletion; or
  3. trick: run the loop backwards, from the end towards the beginning.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by