简体   繁体   English

在 Matlab 数组的每一行中索引相同/不同的元素

[英]Indexing equal/different elements in each row of a Matlab array

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=6 , I could have例如,对于I=3J=6 ,我可以

A=  [0    0      Inf -Inf 0   1; 
     5    4      Inf -Inf 6   5;
     Inf -Inf    0    Inf 0   2];

I want to construct a matrix B of size IxJ , such that each row i starts from 1 , adds a +1 every time an element of A(i,:) changes, and assigns equal index to equal elements.我想构造一个大小为IxJ的矩阵B ,使得每一行i1开始,每次A(i,:)的元素更改时添加+1 ,并将相等的索引分配给相等的元素。 Two Inf elements have to be treated as equal.两个Inf元素必须被视为相等。 Similarly, two -Inf elements have to be treated as equal.同样,必须将两个-Inf元素视为相等。

In the example above在上面的例子中

B=  [1 1 2 3 1 4;  %
     1 2 3 4 5 1;
     1 2 3 1 3 4];

Could you advise on how to proceed?你能建议如何进行吗?

A simple approach is to use the third output of unique with the 'stable' option for each row:一种简单的方法是使用unique的第三个 output 和每行的'stable'选项:

B = NaN(size(A)); % preallocate
for k = 1:size(A,1)
   [~, ~, B(k,:)] = unique(A(k,:), 'stable');
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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