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!