Code to input function

2 次查看(过去 30 天)
Aryan
Aryan 2022-8-29
编辑: Chunru 2022-8-29
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.

回答(2 个)

David Hill
David Hill 2022-8-29
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 2022-8-29
编辑:Chunru 2022-8-29
% 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

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by