Anonymus Function from Input function
이전 댓글 표시
Hi, I am writing a code that takes an input function (f) and then the code does some operations with it. It was using inline function but I prefer to use anonymous function. It was set as f1=inline(f); In order to use the anonymous instead of inline, I changed it to f1 = @(x)[f]; However, after declaring it like this, the code stops working correctly. I don't know what I'm doing wrong.
Thank you
답변 (1개)
Star Strider
2016년 2월 21일
you have to call the inline function as a function.
This works:
f = inline('cos(x) .* sin(x)');
f1 = @(x) f(x);
q = f1(pi/4);
Better is to just do:
f1 = @(x) cos(x) .* sin(x);
댓글 수: 4
Jose Trevino
2016년 2월 21일
Star Strider
2016년 2월 22일
You need to rename and restate the secondary functions, and then change the other references to them in your code:
F = @(x)f(x);
DF = @(x)df(x);
Since MATLAB is case-sensitive, it won’t get confused.
However, you really don’t need to do all that. Something like this will work as well:
f = inline('sin(x) .* cos(x)');
deriv = @(f,x) (f(x+1E-8) -f(x))./1E-8; % Simple Numerical Derivative
x = linspace(0, 2*pi);
figure(1)
plot(x, f(x))
hold on
plot(x, deriv(f,x))
hold off
grid
This is just an illustration. If your functions are function files, you will have to pass them as function handles:
function [ r, error ] = newton( @f, @df, x0, tol, N )
Note the preceding ‘@’ sign, creating the function handles for ‘f’ and ‘df’.
Jose Trevino
2016년 2월 22일
Star Strider
2016년 2월 22일
My pleasure!
If my Answer solved your problem, please Accept it.
카테고리
도움말 센터 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!