Clear Filters
Clear Filters

Use an input for a function

2 views (last 30 days)
Matt Baron
Matt Baron on 27 Mar 2021
Commented: Matt Baron on 27 Mar 2021
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.

Accepted Answer

Stephen23
Stephen23 on 27 Mar 2021
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 Comment
Matt Baron
Matt Baron on 27 Mar 2021
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?

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!