Use an input for a function

조회 수: 1 (최근 30일)
Matt Baron
Matt Baron 2021년 3월 27일
댓글: Matt Baron 2021년 3월 27일
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.

채택된 답변

Stephen23
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'
ans = 1.2000
Note that with the 's' option you can also get rid of those symbolic variables at the start.
  댓글 수: 1
Matt Baron
Matt Baron 2021년 3월 27일
Thank you, perfect. After playing around with it and reading the references here is how I understand it;
's' causes the input to be stored as an unevaluated function
sprintf makes ('@(x,y)%s',dfeq) to input @(x,y) as a string along with dfeq (kind of like you were typing it yourself into the command line)
str2func makes the strings above into a function
Does that sound right?

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Digital Filter Design에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by