Just found this awesome function in Matlab called

`bsxfun`

. It is rather helpful, and fast too as illustrated below. Usage can be found at Matlab documentation (ofcourse!) or an example as below. It is called in a way a little similar to the late (deprecated) `blkproc`

(or now, `blockproc`

) function with an argument as a function. The “@fun” part.
The example here basically computes the difference, B is subtracted from each row of A.

>> A = rand(1000,3);

>> B = rand(1,3);

>> tic; C1 = bsxfun(@minus,A,B); toc;

Elapsed time is 0.003523 seconds.

>> tic; C2 = A - ones(1000,1)*B; toc;

Elapsed time is 0.090703 seconds.

Note that it performs the subtraction on the columns, (length 3). In case you specify B as `B = rand(1000,1)`

then it will perform the subtraction on the rows (length 1000).

Another way to achieve the same operation, without using a loop, would be using `repmat`

, but it is the slowest of them all. Ofcourse, you should NOT even think of using a loop for such a thing in Matlab!

Advertisements