Search code examples
matlabfunctionmatrixscalar

Matlab extend a function on scalar to a function on matrix


In Matlab page array provided a simple method to extend a scalar function $func$ to vector and matrix(and high dimensional tensor), i.e.

B = arrayfun(func,A)

However, when I attempted to do the same, it returned an error

function [output_matrix]=func(y1_matrix)
    output_matrix = arrayfun( func_elementwise  ,y1_matrix);

    function [output_x]=func_elementwise(x1)
    % a scalar function
    ...(Arguments that had been verified worked)
    end

end 

when I attempted to run the function, it returned

Not enough input arguments.
Error in func/func_elementwise 
        x1=mod(x1,2*pi)-pi;

Error in func
output_matrix = arrayfun( func_elementwise  ,y1_matrix);

Could you tell me what went wrong? why arrayfun did not work for func_elementwise? (the attempted inputs for func were scalar and 1*N matrix, both did not work. )


Solution

  • In your code,

    arrayfun(func_elementwise,y1_matrix)
    

    you call the function func_elementwise without arguments:

    func_elementwise
    

    is the same as

    func_elementwise()
    

    You need to pass a function handle to arrayfun, like so:

    arrayfun(@func_elementwise,y1_matrix)