Sorting a matrix from smallest to biggest left to right

19 ビュー (過去 30 日間)
Vinny
Vinny 2016 年 4 月 15 日
コメント済み: Vinny 2016 年 4 月 15 日
I made this code here for a matrix that was only 1 row. Now that I have matrices with multiple rows I don't know how to make it sort from left to right. Right now it sorts from top to bottom.
For example, the third matrix goes
4 7
5 8
6 9
I need it to go
4 5
6 7
8 9
m=numel(a);
for j=1:1:(m-1)
for i=1:1:(m-1)
if a(i)>a(i+1)
temp=a(i);
a(i)=a(i+1);
a(i+1)=temp;
end
end
end
These are some of the matrices I need to work with
a=[3 -2 1;4 0 5;1 2.2 -3]
a=[4 2 1;9 3 5]
a=[9 8;7 6;5 4]
Any help is appreciated. Thank you.

回答 (2 件)

Stephen23
Stephen23 2016 年 4 月 15 日
編集済み: Stephen23 2016 年 4 月 15 日
The trick is to transpose, then use the columnwise element order:
>> M = [4,7;5,8;6,9]
M =
4 7
5 8
6 9
>> tmp = M.';
>> tmp(:) = sort(tmp(:));
>> out = tmp.'
out =
4 5
6 7
8 9
Basically what you are doing is simple, when you think in terms of columns, not rows.
  1 件のコメント
Vinny
Vinny 2016 年 4 月 15 日
The only issue is I can't use built in functions like sort, so I need a way to have it do this in the loop.

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


Andrei Bobrov
Andrei Bobrov 2016 年 4 月 15 日
M = [4,7;5,8;6,9]
out = reshape(M,size(M,2),[])';
  1 件のコメント
Vinny
Vinny 2016 年 4 月 15 日
I've integrated this into the loop and it works and gives me the matrix the way I want it.
for j=1:1:(m-1)
for i=1:1:(m-1)
if a(i)>a(i+1)
temp=a(i);
a(i)=a(i+1);
a(i+1)=temp;
out=reshape(a,size(a,2),[])';
end
end
end
But for this assignment I can't use built in functions like reshape. How can this be done as a loop?

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

カテゴリ

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