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
Star Strider 2016년 2월 21일

0 개 추천

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

Thank you for your answer. I understand the procedure. However, I don't know how to apply it to my code:
function [ r, error ] = newton( f, df, x0, tol, N )
f = @(x)f;
df = @(x)df;
r(1) = x0 - (f(x0)/df(x0));
error(1) = abs(r(1)-x0);
k = 2;
while (error(k-1) >= tol) && (k <= N)
r(k) = r(k-1) - (f(r(k-1))/df(r(k-1)));
error(k) = abs(r(k)-r(k-1));
k = k+1;
end
end
I can't make it run as it should but if I swap to f =inline(f); df = inline (df); it Works. How can I make it work with the anonymous function instead of inline
Thank you again
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
Jose Trevino 2016년 2월 22일
Thank you very much! I got it
Star Strider
Star Strider 2016년 2월 22일
My pleasure!
If my Answer solved your problem, please Accept it.

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

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

질문:

2016년 2월 21일

댓글:

2016년 2월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by