【发布时间】:2014-12-03 13:00:44
【问题描述】:
我有以下矩阵来跟踪数据范围的起点和终点(第一列代表"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 中较大范围内包含的所有范围的最终目标?我不知道我是不是想太多了……
【问题讨论】:
-
这个矩阵有多大?如果不是太大,我看不出成对比较有什么问题
-
myMatrix可能不会超过 100 行左右。问题是我将需要运行大量这些矩阵。 -
如果第一列没有排序怎么办?您的循环解决方案似乎不适用于这种情况。或者您是否假设您的实际数据集不会出现这种情况?
标签: matlab matrix vectorization