matlab - 计算向量的最大值 "running"

标签 matlab matrix vectorization

我有以下矩阵,用于跟踪数据范围的起点和终点(第一列代表 "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 的方法。我查看了 accumarrayfilter,但无法找到使用这些函数的方法。是否有跳过 for 循环的潜在替代方案(某种更高效的矢量化代码)?

2) 是否有一种完全不同(即更有效)的方法来实现删除 myMatrix 中较大范围内包含的所有范围的最终目标?不知道是不是我想多了……

最佳答案

方法#1

bsxfun 基于暴力破解方法 -

myMatrix(sum(bsxfun(@ge,myMatrix(:,1),myMatrix(:,1)') & ...
    bsxfun(@le,myMatrix(:,2),myMatrix(:,2)'),2)<=1,:)

对提议的解决方案的一些解释:

  1. 比较所有 starts 索引的“包含性”,类似地比较 ends 索引。请注意,“包含性”标准必须适用于以下两个中的任何一个:

    • 大于或等于 starts,小于或等于 ends
    • 小于或等于 starts,大于或等于 ends

    我恰好选择了第一个选项。

  2. 查看哪些行至少满足一个“包含性”并删除它们以获得所需的结果。


方法#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/

相关文章:

.net - NET.addAssembly 返回奇怪的 Could 以加载程序集或其依赖项之一

c++ - 如何在不引起递归的情况下使模板特化继承泛型基类?

C++:什么是 Mat3f?

image-processing - 实时 Cuda 图像处理建议

matlab - 双 for 循环的矢量化,包括两个变量的正弦

matlab - MLP 神经网络未正确训练,可能收敛到局部最小值

python - 从原子力显微镜测量计算粒度分布

python - 将一个热行向量的 numpy 数组转换为索引的列向量

R:在没有 for 循环的情况下将函数应用于矩阵的所有行对

numpy - 如何向量化一维数组上的操作以在numpy中生成二维矩阵