Sorting an array of numbers in descending order by using while loop
이전 댓글 표시
I wrote the code to sort number in descending order but my code failed to do so (actually i was the failure lol).
Example: Consider, the given array is x=[4 6 9 2 5 0 1] and i want the output y as [9 6 5 4 2 1 0].
What is more, my thinking was like that in seq-
1) Find maximum number from a given array
2) Then use find function to detect the maximum element idexing
3) And then remove the maximum number from the array and reducing the array length
However, i am successfully failed to do what i am looking for. I am determined to use only the while loop to execute this code (nothing else is appreciable e.g sort function and for loop)
Can anyone tell me where i did wrong while i was writing the code? i mean the erroneous part of the code.
I will be glad if any expert give me an advice or suggestion to correct the the code.
function y =sortingnumsindes(x)
y=[];
while(numel(x)>0)
y=max(x);
p=find(x==y);
x(p)=[];
end
y=x;
end
채택된 답변
추가 답변 (1개)
Guillaume
2020년 5월 4일
"1) Find maximum number from a given array"
"2) Then use find function to detect the maximum element idexing"
Have a look at the documentation of max, in particular the 2nd output which is exactly the index you want.
p=find(x==y);
will work in your code as long as there's only one value equal to the max. If there's more than one, p is a vector of indices and you'll end up deleting too many elements.
y=[];
%...
y=max(x);
%...
y=x;
You need to rethink what y is, you're using it for two purpose, and how you fill it.
댓글 수: 1
Syed Shahed
2020년 5월 4일
편집: Syed Shahed
2020년 5월 4일
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!