Working with an equation and variables from user.

60 次查看(过去 30 天)
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

采纳的回答

James Tursa
James Tursa 2021-3-11
编辑:James Tursa 2021-3-11
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 个评论
James Tursa
James Tursa 2021-3-11
编辑:James Tursa 2021-3-11
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]);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by