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

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?

댓글 수: 2

Can you show a little more context, like how you define the variables x1, x2, x3, and f with which you call MyFunction and what exactly "Matlab[sic] doesn't seem to like this" means?
  1. Does it throw an error, and if so what is the full text of the error message?
  2. Does it issue a warning, and if so what is the full text of the warning message?
  3. Does it return a result different than what you expect?
  4. Does it do something else (and if so, what does it do?)
I'm trying to solve f(x)=0 using a process that uses an iteration. So I have initial values, say 'x1,x2,x3', and I want f to be a generic function of x(i). I use these initial values and f(initial values) to calculate x(4),x(5) and so on. but when I use my function; function res = Myfunction(x1,x2,x3,f) and sub in cos(x) for f Matlab returns Undefined function or variable'x'.
I understand why this happens because x isn't defined but I don't know how to get past this.
For a better example:
I have:
function res = ITERATION(f,x0,x1,n)
% where f is a function
x(2) = x1 + f(x1) + f(x0);
x(3) = x2 + f(x2) + f(x1);
for i = 4:n
x(i) = x(i-1) + f(x(i-1)) + f(x(i-2));
end
for i = 2:n
res(i) = (x(i))^2
end
purely as an example
when I run the new function and sub a function of 'x' it returns 'x' is undefined

댓글을 달려면 로그인하십시오.

 채택된 답변

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)

추가 답변 (0개)

질문:

2016년 11월 7일

댓글:

2016년 11월 9일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by