Use an input for a function
조회 수: 1 (최근 30일)
이전 댓글 표시
Good morning team!
I am trying to prompt the user to input an equation but it seems input just calculates the equation. How do I retain x and y as a variable? The bolded and underlined is the part I am having trouble with.
syms e i r
display("Hello! Welcome to Matt Baron's numerical solver. Press enter to continue.")
pause
choice = input('Press e for Euler, i for Improved Euler, or r for RK4.');
if choice == e
step = input('What step size would you like?');
initcondx = input('What is the initial condition for x?');
initcondy = input('What is the initial condition for y?');
n=0;%start at 0
x=initcondx;%start at the initial condition
y=initcondy;%start at the initial condition
dfeq=input('What differential equation do you want approximated? i.e. .2 * x * y');
f=@(x,y) (dfeq);%the function to be evaluated
actual=@(x) (exp(.1 .* (x .^2) - .1));%the solved function
while x < 1.5%what value do you want it estimated to
x = (initcondx) + ((n) .* (step));
abs = actual(x) - y;
rel = (abs ./ actual(x)) .* 100;
[x y actual(x) abs rel]
y = (y) + ((step) .* f(x,y));
if x >= 1.5
break
end
n=n+1;
end
end
I have also tried;
f=@(x,y) (input('What differential equation do you want approximated? i.e. .2 * x * y'));%the function to be evaluated
Please point me in the right direction.
댓글 수: 0
채택된 답변
Stephen23
2021년 3월 27일
Use the 's' option to return the input unevaluated (i.e. as a character vector):
You then need to use str2func to convert that character vector to a valid function handle:
For example:
pmt = 'What differential equation do you want approximated? i.e. .2 * x * y';
str = input(pmt,'s');
% ^^^ you need this!
fun = str2func(sprintf('@(x,y)%s',str));
fun(2,3) % assuming user entered '0.2*x*y'
Note that with the 's' option you can also get rid of those symbolic variables at the start.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Digital Filter Design에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!