Search code examples
arraysmatlabbsxfun

Matlab bsxfun alternative cause wrong result


I have to run Matlab code on an old version that doesn't support bsxfun and need to write the equivalent expression of

matx = bsxfun(@rdivide, matx, reshape(f, 1, 1, length(f)));

I have tried this

matx=matx./ones(size(reshape(f, 1, 1, length(f)),1));

but I get wrong result

matx size is 246x301x81 f size is 1x81 before the invocation of the istruction that use bsxfun


Solution

  • Since matx is a 3D array and f is a row vector of length equal to the number of elements in dim-3 of matx, you can perform the bsxfun equivalent expansion/replication with repmat and then perform elementwise division like so -

    % Get size of matx
    [m1,n1,r1] = size(matx);
    
    %// Replicate f to the size of matx and perform elementwise division
    matx = matx./repmat(permute(f,[1 3 2]),[m1 n1 1])