필터 지우기
필터 지우기

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
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 8월 29일
Do not use eval for this purpose, use str2func()

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

카테고리

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