variable undefined error while using anonymous function with user input

5 vues (au cours des 30 derniers jours)
M Shajeeh Mustafa
M Shajeeh Mustafa le 6 Fév 2016
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)

Star Strider
Star Strider le 6 Fév 2016
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 Help Center 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