MATLAB:索引到带有移动窗口的矩阵

时间:2018-04-13 10:19:04

标签: matlab indexing

我正在寻找一种有效的方法,以便使用移动窗口索引矩阵。

% 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

1 个答案:

答案 0 :(得分:0)

正如评论中所述,如果没有更多细节,建议真的很难,但您可以尝试使用filter2imfilter函数来处理此类事情。通过更多地描述您想要实现的目标以及为什么,某人可能能够提供更具体的答案