how to assign rank to each row?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2023-9-13
A = [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)])
2 个评论
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]
B = cumsum([1;any(diff(A),2)])
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!