Evaluate gradient for nth variables

조회 수: 3 (최근 30일)
FN
FN 2016년 11월 8일
편집: FN 2016년 11월 8일
Hi I have a script where the user enters a function f(x,y,...) and an initial value vector "X0" with length "n" where n is equal to the number of function variables. After that a variable "grad" is created as grad=gradient(f). I want to calculate grad at this initial value vector but it is not working. f(x,y,...) is symbolic, grad is symbolic and X0 is integer. Anyone can help? I know its a newbie question but it happens....
f(x1,x2)=x1^2-3*x1*x2+4*x2^2+x1-x2;
X0=[2;2];
i=length(X0);
ans=eval(grad(X0(1:i))) -----------Here is the problem
  댓글 수: 1
FN
FN 2016년 11월 8일
편집: FN 2016년 11월 8일
Thanks for the answer but I still have the problem. I think I have not explained well. Consider that I want the user to change only 3 lines of the code:
syms (x1,x2,x3) %enter the number of independent variables (free to change)
f=x1^2+x2^3+4*x1*x2 %the user may enter another function with more variables
V0=[5,5,5] %initial guess the user may enter. first number corresponds to x1, second to x2....
what I need is a piece of code that evaluate the expression f considering the vector V0. And the number of variables on f (and also the size of V0) may change every time someone runs the script.
I think its more clear now. Sorry for the confusion.

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

채택된 답변

Torsten
Torsten 2016년 11월 8일
syms x y
f=x^2-3*x*y+4*y^2+x-y;
grad_f=jacobian(f,[x y]);
gf=@(xx,yy) subs(grad_f,[x,y],[xx,yy]);
gf(2,2)
Best wishes
Torsten.

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by