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?

 Réponse acceptée

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 commentaire

Anthony
Anthony le 2 Nov 2014
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by