Sort using flow control

3 ビュー (過去 30 日間)
Aggie
Aggie 2014 年 9 月 5 日
編集済み: Star Strider 2014 年 9 月 5 日
I am new to MATLAB...first assignment and I have been tasked to build a MATLAB function that is to sort an array of numbers using flow control (smallest to largest). Then I am supposed to return the argument in a new similar array. Can anybody help me at least get started with this task?

回答 (2 件)

Sean de Wolski
Sean de Wolski 2014 年 9 月 5 日
function sorted = mysort(x)
sorted = sort(x);
end
  1 件のコメント
Aggie
Aggie 2014 年 9 月 5 日
I'm not allowed to use any built in MATLAB functions for sorting

サインインしてコメントする。


Star Strider
Star Strider 2014 年 9 月 5 日
This is how I would do the sorting:
x = randi(20,50,1);
x = x(:);
srtd = [];
for k1 = 1:length(x)
[sx,ix] = min(x);
srtd = [srtd; sx];
x(ix) = [];
end
The ‘srtd’ array would be the returned output.
  2 件のコメント
Aggie
Aggie 2014 年 9 月 5 日
Does this output the answer in the same "shape" as the original array?
Thanks
Star Strider
Star Strider 2014 年 9 月 5 日
編集済み: Star Strider 2014 年 9 月 5 日
My pleasure!
You said ‘array’ and I read ‘vector’. This corrects my oversight.
This will work for an (NxM) matrix:
x = randi(50,20,2); % Argument
[ar,ac] = size(x);
for k1 = 1:ac
svct = [];
xa = x(:,k1);
for k2 = 1:ar
[sx,ix] = min(xa);
svct = [svct; sx];
xa(ix) = [];
end
srtd(:,k1) = svct;
end
Run it and see if it works for you. The returned array ‘srtd’ is the same size as ‘x’, the input argument matrix (or vector). If you want to sort in descending order, replace min with max.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by