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!