how to define a gradient vector of a given function?

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

回答(1 个)

Ameer Hamza
Ameer Hamza 2020-12-16
编辑:Ameer Hamza 2020-12-16
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});

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by