0

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.

RobotRaven
  • 130
  • 4
Tom
  • 103
  • 1

2 Answers2

3

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.

mikkola
  • 3,376
  • 1
  • 19
  • 41
  • Thank you. This works, but isn't there another way around? – Tom Nov 22 '15 at 19:21
  • 1
    @Tom why should there be? You want your function to return a vector, which is the same size as `x` but contains only the value 1. That *is exactly* `ones(size(x))`. – Andras Deak -- Слава Україні Nov 22 '15 at 19:23
  • 1
    @Tom I don't see why you'd need something else. The `ones(size(x))` is a generalization of your original approach, since in MATLAB `1` is by most practical purposes equal to `ones(1)`. – mikkola Nov 22 '15 at 19:26
-2

I found a better way of doing this. This shows how stupid Matlab is:

f  = @(x) (x-x)+1

Try it!

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Nacho
  • 1