我有以下矩阵,用于跟踪数据范围的起点和终点(第一列代表 "starts"
,第二列代表 "ends"
):
myMatrix = [
162 199; %// this represents the range 162:199
166 199; %// this represents the range 166:199
180 187; %// and so on...
314 326;
323 326;
397 399;
419 420;
433 436;
576 757;
579 630;
634 757;
663 757;
668 757;
676 714;
722 757;
746 757;
799 806;
951 953;
1271 1272
];
我需要消除矩阵中存在的较大范围内包含的所有范围(即行)。例如 [166:199]
和 [180:187]
包含在 [162:199]
范围内,因此,行需要删除 2 和 3。
我想到的解决方案是在第二列上计算一种“运行”max
,该列的后续值将与该列的后续值进行比较,以确定是否需要删除它们。我使用 for
循环实现了这个,如下所示:
currentMax = myMatrix(1,2); %//set first value as the maximum
[sizeOfMatrix,~] = size(myMatrix); %//determine the number of rows
rowsToRemove = false(sizeOfMatrix,1); %//pre-allocate final vector of logicals
for m=2:sizeOfMatrix
if myMatrix(m,2) > currentMax %//if new max is reached, update currentMax...
currentMax = myMatrix(m,2);
else
rowsToRemove(m) = true; %//... else mark that row for removal
end
end
myMatrix(rowsToRemove,:) = [];
这正确地删除了 myMatrix
中的“冗余”范围并生成以下矩阵:
myMatrix =
162 199
314 326
397 399
419 420
433 436
576 757
799 806
951 953
1271 1272
关于问题:
1) 似乎必须有比 for
循环更好的计算“运行”max
的方法。我查看了 accumarray
和 filter
,但无法找到使用这些函数的方法。是否有跳过 for
循环的潜在替代方案(某种更高效的矢量化代码)?
2) 是否有一种完全不同(即更有效)的方法来实现删除 myMatrix
中较大范围内包含的所有范围的最终目标?不知道是不是我想多了……
最佳答案
方法#1
bsxfun
基于暴力破解方法 -
myMatrix(sum(bsxfun(@ge,myMatrix(:,1),myMatrix(:,1)') & ...
bsxfun(@le,myMatrix(:,2),myMatrix(:,2)'),2)<=1,:)
对提议的解决方案的一些解释:
比较所有
starts
索引的“包含性”,类似地比较ends
索引。请注意,“包含性”标准必须适用于以下两个中的任何一个:- 大于或等于
starts
,小于或等于ends
- 小于或等于
starts
,大于或等于ends
。
我恰好选择了第一个选项。
- 大于或等于
查看哪些行至少满足一个“包含性”并删除它们以获得所需的结果。
方法#2
如果您对根据第一列对行进行排序的输出没有问题,并且局部最大值
的数量较少,您可以尝试这种替代方法 -
myMatrix_sorted = sortrows(myMatrix,1);
col2 = myMatrix_sorted(:,2);
max_idx = 1:numel(col2);
while 1
col2_selected = col2(max_idx);
N = numel(col2_selected);
labels = cumsum([true ; diff(col2_selected)>0]);
idx1 = accumarray(labels, 1:N ,[], @(x) findmax(x,col2_selected));
if numel(idx1)==N
break;
end
max_idx = max_idx(idx1);
end
out = myMatrix_sorted(max_idx,:); %// desired output
关联函数代码-
function ix = findmax(indx, s)
[~,ix] = max(s(indx));
ix = indx(ix);
return;
关于matlab - 计算向量的最大值 "running",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264164/