Matlab bsxfun - Why does bsxfun not work in this case?

My binary function is approximately similar to

func=@(i,j)exp(-32*(i-j)^2);

with grid as follows

[X Y]=meshgrid(-10:.1:10);

Strange, arrayfuncreates the correct result, and bsxfunwill produce records that Inf.

an1=arrayfun(func,X,Y);
an2=bsxfun(func,X,Y);

>> max(max(abs(an1-an2)))
ans = 
     Inf

Why?


EDIT: now that the issue is resolved. I am including some benchmarking data to facilitate a discussion of performance withbsxfun

Assuming the grid is already created using

[X Y]=meshgrid(Grid.partition);
func=@(i,j)exp(-32*(i-j).^2);

(I intend to reuse the grid many times in different places.)

Setting the nesting time of the named functions.

>> tic;for i=1:1000;temp3=exp(-32*bsxfun(@minus,Grid.partition.',Grid.partition).^2);end;toc,clear temp
Elapsed time is 1.473543 seconds.
>> tic;for i=1:1000;temp3=exp(-32*bsxfun(@minus,Grid.partition.',Grid.partition).^2);end;toc,clear temp
Elapsed time is 1.497116 seconds.
>> tic;for i=1:1000;temp3=exp(-32*bsxfun(@minus,Grid.partition.',Grid.partition).^2);end;toc,clear temp
Elapsed time is 1.816970 seconds.

Timing Anonymous Functional Approach

>> tic;for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear temp
Elapsed time is 1.134980 seconds.
>> tic;for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear temp
Elapsed time is 1.171421 seconds.
>> tic;for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear temp
Elapsed time is 1.180998 seconds.

You can see that the anonymous function approach is faster than the nested function approach (excluding time on meshgrid).

If time is on meshgrid,

>> tic;[X Y]=meshgrid(Grid.partition);for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear X Y temp
Elapsed time is 1.965701 seconds.
>> tic;[X Y]=meshgrid(Grid.partition);for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear X Y temp
Elapsed time is 1.249637 seconds.
>> tic;[X Y]=meshgrid(Grid.partition);for i=1:1000;temp=bsxfun(func,X,Y);end;toc,clear X Y temp
Elapsed time is 1.208296 seconds.

Hard to say...

+4
2

, bsxfun func,

func , , - , (-).

. , ^ .^:

func=@(i,j)exp(-32*(i-j).^2);

bsxfun (. @Divakar answer). meshgrid, , , .

+3

, Anonymous Functions bsxfun, - bsxfun -

arr1 = -10:.1:10
an2 = exp(-32*bsxfun(@minus,arr1.',arr1).^2)

OP , bsxfun @minus .

func=@(i,j)exp(-32.*(i-j).^2);

num_iter = 1000;

%// Warm up tic/toc.
for k = 1:100000
    tic(); elapsed = toc();
end

disp('---------------------------- Using Anonymous Functions with bsxfun')
tic
for iter = 1:num_iter
    [X Y]=meshgrid(-10:.1:10);
    an2=bsxfun(func,X,Y);
end
toc, clear X Y an2

disp('---------------------------- Using bsxfuns built-in "@minus"')
tic
for iter = 1:num_iter
    arr1 = -10:.1:10;
    an2 = exp(-32*bsxfun(@minus,arr1',arr1).^2);
end
toc

Runtimes

---------------------------- Using Anonymous Functions with bsxfun
Elapsed time is 0.241312 seconds.
---------------------------- Using bsxfuns built-in "@minus"
Elapsed time is 0.221555 seconds.
+3

All Articles