function A = bsxfun(fh, A, B)
%BSXFUN  Binary Singleton Expansion Function for codistributed array
%   C = BSXFUN(FUN,A,B) applies the element-by-element binary operation
%   specified by the function handle FUN to arrays A and B, with singleton
%   expansion enabled.
%   
%   The corresponding dimensions of A and B must be equal to each other, or 
%   equal to one. Whenever a dimension of A or B is singleton (equal to 
%   one), BSXFUN virtually replicates the array along that dimension to 
%   match the other array. In the case where a dimension of A or B is 
%   singleton and the corresponding dimension in the other array is zero,
%   BSXFUN virtually diminishes the singleton dimension to zero.
%    
%   The size of the output array C is equal to
%   max(size(A),size(B)).*(size(A)>0 & size(B)>0). For example, if
%   size(A) == [2 5 4] and size(B) == [2 1 4 3], then size(C) == [2 5 4 3].
%    
%   Examples:
%   %Subtract the column means from the matrix A:
%   
%   spmd
%       A = codistributed.rand(8);
%       A = bsxfun(@minus, A, mean(A));
%   end
%   
%   %Compute z(x, y) = x.*sin(y) on a grid:
%   spmd
%         x = codistributed.colon(1,10);
%         y = x.';
%         z = bsxfun(@(x, y) x.*sin(y), x, y);
%   end
%    
%   See also BSXFUN, CODISTRIBUTED, function_handle, gather


%   Copyright 2011-2020 The MathWorks, Inc.

    narginchk(3, 3);
    if ~isa(fh, 'function_handle')
        error(message('MATLAB:bsxfun:nonFunctionHandle'));
    end
    elementWiseOpCheckInputs(A, B, ...
        message('MATLAB:bsxfun:arrayDimensionsMustMatch'));
    distributedutil.CodistParser.verifyNonCodistributedInputs({A, B});
    [LPA, LPB, codistr] = elementWiseOpRedistributeInputs(A, B);
    LPA = bsxfun(fh, LPA, LPB);
    A = codistributed.pDoBuildFromLocalPart(LPA, codistr);
end
