Use an input for a function

2 次查看(过去 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.

采纳的回答

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 个)

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by