variable undefined error while using anonymous function with user input

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.

Réponses (1)

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

Catégories

En savoir plus sur Function Creation dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by