Hi!
Im trying to sort the rows of this matrix in decreacing order with all rows with entries containing zeros (in the first nonzero coloum) gathered at the bottom. By using sortrows(A) im able to sort the rows in decreacing order but have no success in gathering the zero rows in the bottom of the matrix.
I hope this clarifies what i mean.
A =
0 2 4
0 1 6
0 0 5
>> sortrows(A)
ans =
0 0 5
0 1 6
0 2 4
But i want the matrix to be sorted in this way. Shown below.
A=
0 1 6
0 2 4
0 0 5
Im Seeking a generall solution, this matrix is just an example

 채택된 답변

Stephen23
Stephen23 2019년 1월 25일

1 개 추천

>> A = [0,2,4;0,1,6;0,0,5]
A =
0 2 4
0 1 6
0 0 5
>> [~,idx] = sortrows([sum(A==0,2),A]);
>> B = A(idx,:)
B =
0 1 6
0 2 4
0 0 5

댓글 수: 3

Viktor Edlund
Viktor Edlund 2019년 1월 25일
Hi!
Thank you for your answer. Could you please walk me through your resoning in that code.
Im very new to matlab, so walkthroughs are appreciated!
Kind regards, Viktor
Stephen23
Stephen23 2019년 1월 26일
편집: Stephen23 2019년 2월 15일
@Viktor Edlund: What I noticed is that you basically want to treat zero as being larger than all other numbers. This leads to two obvious possible solutions:
  1. create a copy of your matrix, change zero to Inf or NaN, then sort.
  2. add a leading column with a count of how many zeros per row, then sort.
For your simple example they will return the same output, but for more complex matrices with zeros distributed throughout, they could return different results. It is up to you to know/decide what algorithm is suitable for your data.
In any case, I picked 2. because it is simple to implement on one line. Here it is broken down into the main operations:
>> A = [0,2,4;0,1,6;0,0,5] % your data matrix.
A =
0 2 4
0 1 6
0 0 5
>> cnt = sum(A==0,2) % count the zeros in each row.
cnt =
1
1
2
>> mat = [cnt,A] % new matrix, first column is zeros count.
mat =
1 0 2 4
1 0 1 6
2 0 0 5
>> [~,idx] = sortrows(mat) % sort rows of new matrix, get sort index.
idx =
2
1
3
>> B = A(idx,:) % use index to sort original data matrix.
B =
0 1 6
0 2 4
0 0 5
Solution 1. could be implemented like this:
>> idx = A==0;
>> B = A;
>> B(idx) = Inf;
>> [B,idy] = sortrows(B);
>> B(idx(idy,:)) = 0
B =
0 1 6
0 2 4
0 0 5
Viktor Edlund
Viktor Edlund 2019년 2월 14일
Thanks alot! Good explaining for a newbie ;)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

질문:

2019년 1월 25일

편집:

2019년 2월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by