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

Respuestas (1)

Star Strider
Star Strider el 21 de Feb. de 2016
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 comentarios

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 el 22 de Feb. de 2016
Thank you very much! I got it
Star Strider
Star Strider el 22 de Feb. de 2016
My pleasure!
If my Answer solved your problem, please Accept it.

Iniciar sesión para comentar.

Categorías

Más información sobre Function Creation en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 21 de Feb. de 2016

Comentada:

el 22 de Feb. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by