我正在寻找一种有效的方法,以便使用移动窗口索引矩阵。
% 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