根据另一列的值 - matlab获取列的所有第一次出现

时间:2018-04-27 21:58:00

标签: matlab unique

m = repmat([0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2;11,11,22,22,33,33,11,11,22,22,33,33,11,11,22,22,33,33],1,2)'

m(:,1)时,我正试图 在我的例子中,我想检索向量:

m(:,2)==11

我认为 0 (from row 1, because it's the first occurrence of (0,11)) 1 (from row 7, because it's the first occurrence of (1,11)) 2 (from row 13, because it's the first occurrence of (2,11)) 0 (from row 19, because it's the next first occurrence of (0,11)) 1 (from row 25, because it's the next first occurrence of (1,11)) 2 (from row 31, because it's the next first occurrence of (2,11)) 可能是此功能,但unique会忽略重复值

unique(m(:,1),'rows')

2 个答案:

答案 0 :(得分:1)

这是一种在没有for循环的情况下获取它的方法:

a = find(m(:, 2) == 11); % index for all 11
repeat = [false; diff(a)==1]; % true if index diff is one
a(repeat) = []; % remove those indices for non-first occurrence
result = m(a, 1); % what you want

答案 1 :(得分:1)

这是另一种方式:

m1 = [0,1,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2,0,0,0,0,0,0,1,1,1,1,1,1,2,2,2,2,2,2; ...
11,11,22,22,33,33,11,11,22,22,33,33,11,11,22,22,33,33,11,11,22,22,33,33,11,11,22,22,33,33,11,11,22,22,33,33]';

它也适用于以下矢量。

{{1}}