简体   繁体   中英

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 .

For example, for I=3 and J=5 , I could have

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. 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 .

If consecutive inf or inf values should count as different

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;
  • ~=0 converts nonzero values to 1 ;
  • [true(size(A,1),1)...] prepends a column of true values;
  • cumsum(..., 2) accumulates the values along each row.

This treats inf values as different because inf-inf , or diff([inf inf] , gives NaN rather than 0 .

If consecutive inf or -inf values should respectively count as equal

Just replace diff(...)~=0 by an expression involving only indexing and ~= :

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM