matlabfunction-handle

Evaluating a constant anonymous function in MATLAB


In Matlab, I generally do things such as

f  = @(x) x.^2;
xx = 0:.1:1;
ff = f(xx);

So that f is a function handle and both xx and ff are 1x11 vectors.

However, if for some reason I need to define my function handle f like this

f  = @(x) 1;

and do not change the code for xx and ff, then xx will still be a vector but ff will NOT: it will be a double.

This is annoying of course, because the sequel of my code assumes that ff is a 11x1 vector, so I would need to change my code any time f happens to be constant.

So my first question is whether or not my code is sound to begin with. If so, what should I do to make it work in the "constant f" case? If not, how should I rewrite it?

This is admittedly similar to matlab constant anonymous function returns only one value instead of an array but I can't quite find an answer in that thread.


Solution

  • A minor modification of the answer you linked will provide the required result:

    f = @(x) ones(size(x));
    

    The size of f(x) will match the size of the input x since f outputs a vector of ones the same size as x.