Gradient of a function of two variables?

7 Ansichten (letzte 30 Tage)
DIEGO FOSSO
DIEGO FOSSO am 13 Jul. 2015
Beantwortet: Bjorn Gustavsson am 13 Jul. 2015
Hi, I would like to manually compute the gradient of this math function: f(x, y) = x^2 + 2*x*y − x*y^2 and I would like to write the result in the command window as input of a Matlab function. I wrote the f(x,y) as
f=inline('x^2 + 2*x*y − x*y^2','x','y')
I know the gradient is ∇f(x, y)= (2*x + 2*y − y^2, 2*x − 2*x*y). Does anyone know how can I write it in the command window? (because that's not a common vector)

Antworten (1)

Bjorn Gustavsson
Bjorn Gustavsson am 13 Jul. 2015
If you want a symbolic-like gradient you'll have to do it with symbolic variables:
syms x y
F = x^2 + 2*x*y x*y^2
dF = gradient(F)
From there you might generate m-functions, see matlabFunction (If you don't have access to the symbolic toolbox look at the file exchange for a submission by John d'Errico that does symbolic operations (on polynomials only?))
If you want to work with numerical calculations in the end you can use the gradient function. But then I'd guess you'd need to vectorize your function:
f = inline(x.^2+3*x.*y,'x','y')
or preferably start using anonymous functions instead of inline:
f = @(x,y) x.^3 - 3*x.*y.^3
If you want to create a function for the gradient operator you might get something like this to do what you want:
gF = @(f,x,y) gradient(f(x,y),x(1,:),y(:,1))
But then you're venturing into a region where you should give the chebfun (also found on the file exchange) project some consideration.
HTH

Community Treasure Hunt

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

Start Hunting!

Translated by