[英]Construct a matrix in Matlab that keeps track of equal elements in each row
Suppose I have a IxJ
matrix A
in Matlab which contains some numbers (possibly, including Inf
, -Inf
.假设我在 Matlab 中有一个
IxJ
矩阵A
,其中包含一些数字(可能包括Inf
, -Inf
。
For example, for I=3
and J=5
, I could have例如,对于
I=3
和J=5
,我可以有
A= [0 0 0 Inf -Inf;
5 4 0 Inf -Inf;
Inf -Inf 0 0 0];
I want to construct a matrix B
of size IxJ
, such that each row i
starts from 1
and adds a +1
every time an element of A(i,:)
changes.我想构造一个大小为
IxJ
的矩阵B
,这样每一行i
从1
开始,并且每次A(i,:)
的元素发生变化时都添加一个+1
。 In the example above在上面的例子中
B= [1 1 1 2 3; %
1 2 3 4 5;
1 2 3 3 3];
Could you advise on how to proceed?你能建议如何进行吗?
That's easy to do with diff
and cumsum
.使用
diff
和cumsum
很容易做到这一点。
inf
or inf
values should count as differentinf
或inf
值应计为不同B = cumsum([true(size(A,1),1) diff(A,[],2)~=0], 2);
It works as follows:它的工作原理如下:
diff(A,[],2)
takes consecutive differences along each row; diff(A,[],2)
沿每一行取连续的差异;~=0
converts nonzero values to 1
; ~=0
将非零值转换为1
;[true(size(A,1),1)...]
prepends a column of true
values; [true(size(A,1),1)...]
在前面添加一列true
值;cumsum(..., 2)
accumulates the values along each row. cumsum(..., 2)
沿每一行累积值。 This treats inf
values as different because inf-inf
, or diff([inf inf]
, gives NaN
rather than 0
.这将
inf
值视为不同,因为inf-inf
或diff([inf inf]
给出NaN
而不是0
。
inf
or -inf
values should respectively count as equalinf
或-inf
值应分别计为相等Just replace diff(...)~=0
by an expression involving only indexing and ~=
:只需将
diff(...)~=0
替换为仅涉及索引和~=
的表达式:
B = cumsum([true(size(A,1),1) A(:,1:end-1)~=A(:,2:end)], 2);
This treats inf
values as equal because inf==inf
gives true
, or equivalently inf~=inf
gives false
, and similarly for -inf
.这将
inf
值视为相等,因为inf==inf
给出true
,或者等效地inf~=inf
给出false
,对于-inf
也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.