Working with an equation and variables from user.

조회 수: 68 (최근 30일)
Patrik Matta
Patrik Matta 2021년 3월 11일
댓글: Patrik Matta 2021년 3월 11일
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]);
Patrik Matta
Patrik Matta 2021년 3월 11일
Thank you, this was very helpful.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numbers and Precision에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by