MATLAB: Bsxfun(minus) vs normal minus

bsxfun

i have X=eye(3) and A=magic(3) What is the difference between Result1=A-X and the Result2 with this loop
for i=1:3
Result2=bsxfun(@minus,A,X(i,:));
end

Best Answer

Have you read the documentation of bsxfun?
Input arrays, specified as scalars, vectors, matrices,
or multidimensional arrays. Inputs A and B must have
compatible sizes. For more information, see Compatible
Array Sizes for Basic Operations. 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.
This means the following:
A=[1 2];% 1 by 2
B=[3;4];% 2 by 1
%A will be replicated along the first dimension to make it match B
%B will be replicated along the second dimension to make it match A
%then an element-wise operation can be performed:
C1=bsxfun(@minus,A,B);
C2=repmat(A,size(B,1),1)-repmat(B,1,size(A,2));