Matrix sorting, smallest to biggest

39 ビュー (過去 30 日間)
Vinny
Vinny 2016 年 4 月 15 日
コメント済み: James Tursa 2016 年 4 月 15 日
So I need to sort a matrix from smallest to biggest going from left to right, with multiple rows. I was told in a previous thread about sort and reshape, which when I integrate into my loop work, but for this assignment I'm doing I can't use built in functions like that. I have to sort the function as part of a loop.
This loop sorts all my matrices but only from top to bottom.
It does stuff like this
1 4 7
2 5 8
3 6 9
I need it to do this
1 2 3
4 5 6
7 8 9
What do I need to add or change to make it go from left to right, like reading a book.
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
I can't just straight up use functions like this
out = reshape(a,size(a,2),[])';
I wish I could but that's not allowed for this.
Here are the 3 matrices I'm working 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]
Anything is appreciated. Thank you.

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 4 月 15 日
編集済み: Azzi Abdelmalek 2016 年 4 月 15 日
reshape(sort(A(:)),fliplr(size(A)))'

James Tursa
James Tursa 2016 年 4 月 15 日
編集済み: James Tursa 2016 年 4 月 15 日
After your loop, add this line:
a = a';
The reason you are getting the result column-ordered instead of row-ordered is because MATLAB matrix memory is stored in column-order and linear indexing (which you are doing in a loop) will access the elements in that order. So a simple transpose at the end will change the result to row-ordered.
  2 件のコメント
Vinny
Vinny 2016 年 4 月 15 日
編集済み: Vinny 2016 年 4 月 15 日
It works, but for the last 2 vectors I posted its turning the 2x3 vector into a 3x2 and the 3x2 vector into a 2x3. Why is it doing this to those 2, I can't get it to display in the proper format.
James Tursa
James Tursa 2016 年 4 月 15 日
Use Azzi's answer with your result. E.g., put this line after your loops:
a = reshape(a,fliplr(size(a)))';

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by