variable undefined error while using anonymous function with user input
2 次查看(过去 30 天)
显示 更早的评论
Well. i want to write a program that accepts an equation in variables x & y. then using anonymous function, i tried to solve the given equation. But it says x and y undefined. my code is:
h=input('enter an equation in x and y: ');
myfunction = @(x,y) h;
x = 1;
y = 10;
z = myfunction(x,y);
disp(z);
Is there any way to input the equation and solve using anonymous function. Also i don't want to use 'inline' function since it'll be removed in future releases.
I've also tried syms x; But in that case it doesn't substitute 'x' with '1'. had to use subs() command. and subs() does't replace 2 variables i.e. it is for one variable replacement only.
0 个评论
回答(1 个)
Star Strider
2016-2-6
You need to have the input as a string (I prefer the inputdlg function for this) and then use the str2func function to create the function handle.
This works:
hc = inputdlg('enter an equation in x and y: ');
myfunction = str2func(['@(x,y)' hc{:}]);
x = 1;
y = 10;
z = myfunction(x,y);
disp(z);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!