matlabbsxfun

Apply function by column with several inputs in matlab


Apply a function over a matrix using several columns as arguments to apply function with several imputs.

A = [1 2 3];
B = [4 5 6];
C = [7 8 9];

% This is the function I want use,
bsxfun(@(x,y,z) 1/(sqrt(2*pi*z)) * exp((-(x-y).^2)/(2*z)), A, B, C)

But is not working, only works with two imputs:

bsxfun(@(x,y) x+y, A, B)

The error ouput of bsxfun is:

error: Invalid call to bsxfun.  Correct usage is:

 -- bsxfun (F, A, B)

which is telling that i can not do this with more than 2 inputs..

The expected calculation of the function is basically:

[1/(sqrt(2*pi*C1))*exp((-(A1-B1).^2)/(2*C1))
    1/(sqrt(2*pi*C2))*exp((-(A2-B2).^2)/(2*C2))
    1/(sqrt(2*pi*C3))*exp((-(A3-B3).^2)/(2*C3))]

being A1,B1,C1 the first element of A,B,C respectively to N being N the number of elements of the vectors(with same length)

result = [ 0.079 0.08 0.08 ]

Solution

  • You do not need bsxfun here. You just need to define the function handle appropriately.

    f =  @(x,y,z) 1./(sqrt(2*pi*z)).*exp((-(x-y).^2)./(2*z));
    

    Now your expected result is:

    f(A,B,C)