How to sort a matrix using loops?

조회 수: 4 (최근 30일)
Michael Porter
Michael Porter 2016년 4월 16일
편집: John BG 2016년 4월 24일
I need to sort a matrix from least to greatest without the sort function. It needs to be done in nested loops. For example, I need to take the matrix [9 5;7 4;8 6] and sort it into [4 5;6 7;8 9].
  댓글 수: 1
Roger Stafford
Roger Stafford 2016년 4월 17일
See this site for a variety of possible algorithms you might use:
https://en.wikipedia.org/wiki/Sorting_algorithm

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

답변 (1개)

John BG
John BG 2016년 4월 17일
편집: John BG 2016년 4월 17일
Michael
1 for loop is enough
A=randi([-10 10],5,6) % generate input
B=A(:)' % reshape A into straight line
L=length(B)
C=[]
for k=1:L
v=find(B==max(B)) % in case repeated values
C=[C B(v(1))]
B(v(1))=[]
end
If you find this answer of any help solving your question, please click on the thumbs-up vote link, or mark it as accepted answer
thanks in advance
John
  댓글 수: 2
Jan
Jan 2016년 4월 17일
The missing pre-allocation is a bad programming style.
John BG
John BG 2016년 4월 17일
편집: John BG 2016년 4월 24일
Actually, you are right, there are other ways to build the variable collecting the result, some good habits die hard, like declaring variables before using them.
The 'bad' you mention, why? Because it's going to size some more bytes disk?

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

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by