【问题标题】:MATLAB: Indexing into a matrix with a moving windowMATLAB:索引到具有移动窗口的矩阵
【发布时间】:2018-04-13 10:19:03
【问题描述】:

我正在寻找一种有效的方法来使用移动窗口对矩阵进行索引。

% Create logical matrix
startRows = repmat([10,10,30,10,40], 1, 3);

logicalMat = true(100, 5, 3);
logicalMat((1:100)' < startRows) = 0;

% Create source matrix
window = 10;
sourceMat = randi(10, [100, 5, 3]);
sourceMat((1:100)' < startRows-(window-1)) = NaN;

% Compute target matrix: For every cell in targetMat, where logicalMat is true,
% compute the product of multVec and the previous 10 rows.
targetMat = nan(100,5);
multVec = randi(10, [1, 10]);
% For instance, targetMat(10,1) should be the product of multVec and sourceMat(1:10,1).
% targetMat(11,1) = multVec * sourceMat(2:11, 1) and so on...
% targetMat(30,3) = multVec * sourceMat(21:30, 3) and so on...
% I am interested in the technique how to address the "moving window". 

一种可能的解决方案可能是使用 for 循环。但是,我想知道是否存在更优雅的解决方案。此外,如果我将示例扩展到第三维,我将需要第三个 for 循环。是否可以将这个问题向量化?

% Possible solution using loop
[nRows, nCols, nPages] = size(sourceMat);
for p = 1 : nPages
    for c = 1 : nCols
        for r = startRows(c) : nRows
            targetMat(r, c, p) = multVec * sourceMat((r - window + 1) : r, c, p);
        end
    end
end

【问题讨论】:

  • 实际代码中的复杂计算量是多少? sum 的解决方案不一定适用于您的复杂计算。还请展示您尝试过的内容
  • @SardarUsama 在实际代码中,我需要将一个 1x10 向量与相应的移动窗口相乘。我正在尝试使用 for 循环,但我认为这不是最好的方法。
  • 您应该创建一个示例来反映您实际处理的内容。还请展示您尝试过的内容
  • @Andi for 循环可能不是“最好”的方式(虽然循环本身并不慢),但它比不工作的代码要好得多......如果你能得到一个带有简单循环的工作示例来显示预期的输入和输出,然后优化/改进更容易提出建议。
  • @SardarUsama 我在使用 3D 矩阵时提供了一个完整的示例。我想知道向量化for循环是否有意义?很抱歉经常编辑原始问题。这不是要浪费你的时间!

标签: matlab indexing


【解决方案1】:

正如 cmets 中所述,如果没有更多细节,真的很难给出建议,但您可以尝试使用 filter2imfilter 函数来处理这类事情。通过更多地描述您要达到的目标以及原因,有人可能会给出更具体的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多