Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to apply function to every submatrix of a given size in MATLAB

In MATLAB, I want to apply a function to each submatrix of the given size of a matrix.

My current code works but is very slow.

%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

Any suggestions are greatly appreciated!

like image 270
user2752148 Avatar asked Dec 07 '25 03:12

user2752148


1 Answers

If you have the image processing toolbox, you can use blockproc to apply f on a [h w] sliding window of M:

out = blockproc(M, [h w], f);
like image 84
tdy Avatar answered Dec 08 '25 23:12

tdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!