Documentation from Matlab:
Bsxfun:
Apply element-by-element binary operation to two arrays withsingleton expansion enabled.
Repmat:
Replicate and tile an array.
Overview:
There are two approaches to apply element-by-element binary operation to two arrays with singleton expansion enabled, using bsxfun directly or applying repmat first and then make binary operation.
Example:
> A = rand (3, 2)
A =
0.8721 0.3843
0.9016 0.0373
0.9518 0.9271
> B = zeros (3, 1)
B =
0
0
0
> Bsxfun (@ minus, a, B) % operation with singleton expansion enabled
Ans =
0.8721 0.3843
0.9016 0.0373
0.9518 0.9271
> A-B % operation with singleton expansion disabled
Error using-
Matrix dimensions must agree.
> A-repmat (B, 1, 2)
Ans =
0.8721 0.3843
0.9016 0.0373
0.9518 0.9271
Speed test:
Below is a speed test of the two approaches. Please find code at Appendix 1.
As shown in the graph, bsxfun is almost twice faster than repeat.
Why bsxfun is faster:
There are two reasons why bsxfun is faster than the other approach:
1. bsxfun avoids explicit allocation of memory and actual replication of the array;
2. bsxfun is one of the multi-threaded Matlab functions.
FurthermZ? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcmUuLi48L3N0cm9uZz48YnI + hour =" http://www.2cto.com/uploadfile/Collfiles/20140417/20140417092223188.png "alt =" \ ">
As shown in the graph, there is no need to replace normal element-by-element operation with bsxfun.
Appendix 1.
Comparison of bsxfun and repmat.
Clear;
N = 300;
K = 1;
A = ones (10, 1 );
Repmat_result = zeros (n, 1 );
Bsxf_result = zeros (n, 1 );
Num_repeat = 100;
Tt = zeros (num_repeat, 1 );
For I = 1: n;
R = rand (1, I * k );
For it = 1: num_repeat;
Tic,
X = bsxfun (@ plus, a, r );
Tt (it) = toc;
End;
Bsxf_result (I) = mean (tt)/n;
For it = 1: num_repeat;
Tic,
Y = repmat (a, 1, I * k) + repmat (r, 10, 1 );
Tt (it) = toc;
End;
Repmat_result (I) = mean (tt)/n;
End
Plot (bsxf_result, "-R ')
Hold on
Plot (repmat_result, '-B ')
Legend ('bsxfun ', 'refermat') xlabel ('complexity ') ylabel ('speed ')
Title ('speed test of element-by-element binary operation ')
Appendix 2.Comparison of normal binary operation and bsxfun.
Clear;
N = 300;
K = 1;
Repmat_result = zeros (n, 1 );
Bsxf_result = zeros (n, 1 );
Num_repeat = 100;
Tt = zeros (num_repeat, 1 );
For I = 1: n;
R = rand (k, I * k );
For it = 1: num_repeat;
Tic,
X = bsxfun (@ plus, r, r );
Tt (it) = toc;
End;
Bsxf_result (I) = mean (tt)/n;
For it = 1: num_repeat;
Tic,
Y = r + r;
Tt (it) = toc;
End;
Repmat_result (I) = mean (tt)/n;
End
Plot (bsxf_result, '-R ')
Hold on
Plot (repmat_result, '-B ')
Legend ('bsxfun ',' + ')
Xlabel ('complexity ') ylabel ('speed ')
Title ('speed test of element-by-element binary operation ')