当前位置: 动力学知识库 > 问答 > 编程问答 >

sorting - How to do a ~= vector operation in matlab

问题描述:

I'm trying to write my own program to sort vectors in matlab. I know you can use the sort(A) on a vector, but I'm trying to code this on my own. My goal is to also sort it in the fewest amount of swaps which is kept track of by the ctr variable. I find and sort the min and max elements first, and then have a loop that looks at the ii minimum vector value and swaps it accordingly.

This is where I start to run into problems, I'm trying to remove all the ii minimum values from my starting vector but I'm not sure how to use the ~= on a vector. Is there a way do this this with a loop? Thanks!

clc;

a = [8 9 13 3 2 8 74 3 1] %random vector, will be function a once I get this to work

[one, len] = size(a);

[mx, posmx] = max(a);

ctr = 0; %counter set to zero to start

%setting min and max at first and last elements

if a(1,len) ~= mx

b = mx;

c = a(1,len);

a(1,len) = b;

a(1,posmx) = c;

ctr = ctr + 1;

end

[mn, posmn] = min(a);

if a(1,1) ~= mn

b = mn;

c = a(1,1);

a(1,1) = b;

a(1,posmn) = c;

ctr = ctr + 1;

end

ii = 2; %starting at 2 since first element already sorted

mini = [mn];

posmini = [];

while a(1,ii) < mx

[mini(ii), posmini(ii - 1)] = min(a(a~=mini))

if a(1,ii) ~= mini(ii)

b = mini(ii)

c = a(1,ii)

a(1,ii) = b

a(1,ii) = c

ctr = ctr + 1;

end

ii = ii + 1;

end

分享给朋友:
您可能感兴趣的文章:
随机阅读: