Clear Filters
Clear Filters

Working with an equation and variables from user.

21 views (last 30 days)
Hello, I would like to get equation of two variables (x,y) from user's input. 'Enter the equation f(x,y): '. Then ask user for value of each variable 'Set value of x: ' and 'Set value of y: '. When all variables are in I want to evaluate the equation with variables. After this is it possible to countinue to work with the equation, to make a partial derivative evaluate that etc.? I'll be gratefull for any advice.
str1 = input('Enter and equation f(x,y); ','s');
x = input('Set the value of x: ');
y = input('Set the value of y: ');
% the rest was unsuccessful in my code

Accepted Answer

James Tursa
James Tursa on 11 Mar 2021
Edited: James Tursa on 11 Mar 2021
You can construct a function handle as follows:
f = str2func(['@(x,y)' str1]);
You can then use this function handle to evaluate at specific values of x and y.
If you want to take derivatives of this downstream in your code, you could create symbolic expressions to work with. E.g.,
syms x y
fxy = f(x,y)
  6 Comments
James Tursa
James Tursa on 11 Mar 2021
Edited: James Tursa on 11 Mar 2021
If you want to work with both numeric and symbolic at the same time, then pick different variable names for them. E.g., let small case x and y be the symbolic and upper case X and Y be numeric. Then you can work with both at the same time. You can use the subs( ) function to get numeric values into a symbolic expression. E.g.,
str1 = input('Enter f(x,y); ','s');
f = str2func(['@(x,y) ' str1]);
% Use f with numeric variables X and Y (uppercase)
X = input('Set x: ');
Y = input('Set y: ');
disp('Numeric Results:');
fprintf('%s evaluated at x = %d and y = %d = %d\n',str1,X,Y,f(X,Y));
% Use f with symbolic variables x and y (lowercase)
disp('Symbolic Results:');
syms x y
F_xy = f(x,y);
disp('Expression:')
disp(F_xy);
disp('Derivative with respect to x:')
disp(diff(F_xy,x));
fprintf('Evaluated at x = %d and y = %d\n',X,Y);
subs(diff(F_xy,x),[x y],[X Y]);
disp('Derivative with respect to y:')
disp(diff(F_xy,y));
fprintf('Evaluated at x = %d and y = %d\n',X,Y);
subs(diff(F_xy,y),[x y],[X Y]);

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!