Can anyone help me with for loops in Matlab?

I am trying to write a program that uses selection sort to sort an array. I can't use sort or rowsort. I have to make my own function. A user will select a single column of the array to sort. That column will be sorted in ascending order. All rows should move with the selected column so that the original rows match the new sorted column.
My program is attached as well as a working program using the intrinsic functions of Matlab. So, far I can make this work until the eight value of the selected column and then the data is random. I think my for loops are incorrect can anyone help?

 채택된 답변

Roger Stafford
Roger Stafford 2014년 11월 2일

1 개 추천

Here is code for doing selection sorting, Anthony. However, as it stands it works only on a single column vector and does not include entire rows in its swapping process. What you need to do is modify the swap so as to accomplish this latter action. It won't be hard to do. You have to do a swap between entire rows instead of between two scalar quantities.
Here is the code for sorting a single column vector v:
n = size(V,1);
for k = 1:n-1
[t,p] = min(v(k:n)); % The minimum will be located at p+k-1 in v
v(p+k-1) = v(k); % Do a swap between v(p+k-1) and v(k)
v(k) = t;
end
When this exits, v will have been sorted.
To make this work for your purposes your array(:,col) will be v. When you get p from the 'min' call you have to put the entire row into temp:
temp = array(p+k-1,:)
and then
array(p+k-1,:) = array(k,:)
and so forth.
Note that having to do this swapping of entire rows makes selection sorting particularly inefficient as opposed to other algorithms.

댓글 수: 1

Anthony
Anthony 2014년 11월 2일
My problem was not understanding the increments of for loops. Once I realized that the rest was easy. Your original solution using intrinsic functions led me to a method that worked. Thank you.

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

추가 답변 (0개)

카테고리

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

제품

질문:

2014년 11월 2일

댓글:

2014년 11월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by