MATLAB: When writing user defined functions how can i have a function of a variable as an input variable

user defined functions

I am trying to write a function for example: function res = MyFunction(x1,x2,x3,f)
where f is a function of x but Matlab doesn't seem to like this. Is there a way around this without previously defining a function?

Best Answer

If you're doing something like:
res = ITERATION(cos(x),x0,x1,n)
that will not work. MATLAB will try to evaluate the expression cos(x) and pass the result into ITERATION as the first input. But x may not be defined, and it's certainly not going to do what you want based on the way ITERATION is written. Instead pass a function handle into ITERATION as the first input argument.
res = ITERATION(@cos, x0, x1, n)
If instead the function were f(x) = x+1, use an anonymous function:
res = ITERATION(@(x) x+1, x0, x1, n)