Code to input function

I want to make a code where user can input the the function and as the output they get plot of f(x) vs x and also the roots of that non linear equation.

Respuestas (2)

David Hill
David Hill el 29 de Ag. de 2022

1 voto

Plotting would not be a problem, but finding all the roots is a problem. Recommend looking at fzero
a=input('Function (example: @(x)x.*cos(x)-x.^2.*sin(x)+exp(-x)): ','s');
f=str2func(a);
x=-pi:.001:2*pi;
plot(x,f(x));
Chunru
Chunru el 29 de Ag. de 2022
Editada: Chunru el 29 de Ag. de 2022
% fstr = input("Key in a function of x (eg. x.^2 + 2*x - 1): ", "s")
fstr = "@(x) x.^2 + 2*x - 1"; % This is for on-line matlab
try
% eval("f = "+ fstr )
f = str2func(fstr)
fplot(f)
x1 = fzero(f, 0)
title(fstr + ": x1="+x1)
end
f = function_handle with value:
@(x)x.^2+2*x-1
x1 = 0.4142

1 comentario

Walter Roberson
Walter Roberson el 29 de Ag. de 2022
Do not use eval for this purpose, use str2func()

Iniciar sesión para comentar.

Categorías

Más información sobre 2-D and 3-D Plots en Centro de ayuda y File Exchange.

Productos

Versión

R2022a

Etiquetas

Preguntada:

el 29 de Ag. de 2022

Editada:

el 29 de Ag. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by