删除具有相同第一列和最小第二列的行

时间:2016-08-26 23:25:35

标签: arrays matlab

我有两列列表。第一列是主题编号,第二列是会话编号(即当主题第二次进入时,会话编号为2,每次访问都是如此)。

SubMasterList = [6004 1; 6004 2; 6008 1; 6008 2; 6010 1; 6012 1; 6012 2; 6012 3]

我希望SubMasterList只包含会话编号最大的主题的一行(第2列)。似乎是:

SubMasterList = [6004 2; 6008 2; 6010 1; 6012 3]

3 个答案:

答案 0 :(得分:6)

您可以使用sortrows,然后使用unique

的第二个输出从该数组中提取索引
SubMasterList = [6004 1; 6004 2; 6008 1; 6008 2; 6010 1; 6012 1; 6012 2; 6012 3];
tmp = sortrows(SubMasterList,-2); %sort, with descending order to ensure the highest number is on top
[~,idx,~]=unique(tmp(:,1)); %extract indices
Result = tmp(idx,:) %index the sorted array to obtain the result

Result =
        6004           2
        6008           2
        6010           1
        6012           3

答案 1 :(得分:4)

你想要的几乎是accumarray的定义:-)只需使用unique根据矩阵的第一列获取标签,并将其作为第一个输入传递给accumarray

[x, ~, u] = unique(SubMasterList(:,1));
y = accumarray(u, SubMasterList(:,2), [], @max);
result = [x y];

答案 2 :(得分:2)

@Adriaan的回答可能效率不高:

A = [6004 1; 6004 2; 6008 1; 6008 2; 6010 1; 6012 1; 6012 2; 6012 3];

[C,~,ic] = unique(A(:,1));
B = A(:,2);
for ii=1:max(ic)
    D(ii,1) = max(B(ic==ii));
end
SubMasterList = [C D]; 


SubMasterList =

        6004           2
        6008           2
        6010           1
        6012           3
相关问题