在 MATLAB 中,我想对给定大小的矩阵的每个子矩阵应用一个函数。
我当前的代码可以运行,但速度很慢。
%inputs
% f: function to apply to submatrices
% M: main matrix
% h: height of submatrices
% w: width of submatrices
%output
% out: matrix of results of applying f to submatrices of M
function out = metricmap(f,M,h,w)
[r,c] = size(M);
h = h-1;w = w-1; %to make these values deltas
out = zeros([r,c]-[h,w]);
for i = 1:(r - h)
for j = 1:(c - w)
subM = M(i:(i+h),j:(j+w));
out(i,j) = f(subM);
end
end
end
非常感谢任何建议!
最佳答案
如果你有图像处理工具箱,你可以使用blockproc
在 M
的 [h w]
滑动窗口上应用 f
:
out = blockproc(M, [h w], f);
关于performance - 在 MATLAB 中将函数应用于给定大小的每个子矩阵的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66662475/