how to define a gradient vector of a given function?
1 view (last 30 days)
Show older comments
Hello everybody! I have a function from R^n to R and I have computed its gradient (manually!) now I need to implement an array wich contains in each row the i-th partial derivative that I have manually computed and I don't know how to write it. Every partial derivative is the same and it's equal to x_i^2+2. I could write myself the vector with @(x) [df/dx1(x); df/dx2(x);....] but n is very large so i cannot do like this. What's the best way to do the task i need to do?
0 Comments
Answers (1)
Ameer Hamza
on 16 Dec 2020
Edited: Ameer Hamza
on 16 Dec 2020
You can calculate the analytical expression of gradient using the Symbolic Toolbox. For example,
syms x [10 1]
y = sum(x.^3)/3 + 2*sum(x);
dy = gradient(y)
Result
>> dy
dy =
x1^2 + 2
x10^2 + 2
x2^2 + 2
x3^2 + 2
x4^2 + 2
x5^2 + 2
x6^2 + 2
x7^2 + 2
x8^2 + 2
x9^2 + 2
To convert a numeric function handle, using matlabFunction()
dy_fun = matlabFunction(dy, 'Vars', {x});
0 Comments
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!