how to assign rank to each row?

조회 수: 2 (최근 30일)
Rounak Saha Niloy
Rounak Saha Niloy 2023년 9월 13일
편집: Stephen23 2023년 9월 13일
I have a matrix as follows:
A=[1 4;
1 4;
4 1;
4 1;
2 2;
2 3;
2 3;
3 2;
3 3];
I want to have another matrix like this-
B=[1;1;2;2;3;4;4;5;6];
Basically, I want to check each row and increase the corresponding value by 1 if iot does not matches with the preceding one. if it matche with the preceding one, I want to keep it as before.
How can I do this?
  댓글 수: 1
Torsten
Torsten 2023년 9월 13일
편집: Torsten 2023년 9월 13일
For beginners, a for loop over the rows of A, inside the loop: a comparison of row i with row i-1 and an if-statement that adds 1 to element B(i-1) to get element B(i) if the two rows are not equal and that sets B(i) to B(i-1) if they are equal.

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

채택된 답변

Stephen23
Stephen23 2023년 9월 13일
A = [1,4;1,4;4,1;4,1;2,2;2,3;2,3;3,2;3,3]
A = 9×2
1 4 1 4 4 1 4 1 2 2 2 3 2 3 3 2 3 3
B = cumsum([1;any(diff(A,1,1),2)])
B = 9×1
1 1 2 2 3 4 4 5 6
  댓글 수: 2
Les Beckham
Les Beckham 2023년 9월 13일
Note that diff(A,1,1) is the same as diff(A) so this can be simplified as
A = [1,4;1,4;4,1;4,1;2,2;2,3;2,3;3,2;3,3]
A = 9×2
1 4 1 4 4 1 4 1 2 2 2 3 2 3 3 2 3 3
B = cumsum([1;any(diff(A),2)])
B = 9×1
1 1 2 2 3 4 4 5 6
Stephen23
Stephen23 2023년 9월 13일
편집: Stephen23 2023년 9월 13일
"Note that diff(A,1,1) is the same as diff(A) so this can be simplified as"
Not quite. Consider what happens if one day A happens to have exactly one row... my code still works correctly for any size of matrix A, whereas not specifying the dimension is a latent bug.
For the same reason experienced MATLAB users often prefer to specify the (optional) dimension with many common functions e.g. MAX, MIN, MEAN, etc. when used with non-vector data.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by