Find numerical gradient of a function

2 次查看(过去 30 天)
function [y] = sumsqu(xx)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUM SQUARES FUNCTION
%
% INPUT:
%
% xx = [x1, x2, ..., xd]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
d = length(xx);
sum = 0;
for ii = 1:d
xi = xx(ii);
sum = sum + ii*xi^2;
end
y = sum;
end
Above is the code for d variables. Whenever I call the function I get the sum as expected. Now I want to find the numerical gradient of the function. But since the function is returning a scalar value, gradient is returning 0 obviously. What can I do so that gradient first evaluates in its variable form then return an array corresponding to x1 x2 x3....xd?
As you can see in the picture, I want it in that order. And I also want d as a variable so that code can be generic. Hope you understood my problem. Thank you

回答(1 个)

Star Strider
Star Strider 2018-9-29
If I understand correctly what you want to do, this is one approach:
xx = randi(9,1,3) % Create ‘x’ Argument
cfs = (1:numel(xx)) % Coefficient Vector
f = (xx.^2).*cfs % Calculate ‘f’
delf = xx .* (cfs*2) % Calculate Gradient
fsum = sum(f) % Calculate Sum Of ‘f’
Please do not name your variable ‘sum’. This is the name of an important built-in function, and ‘overshadowing’ it with a function name will cause you significan problems if you then want to use the function later in your code.
  2 个评论
Tusar Jit Medhi
Tusar Jit Medhi 2018-9-29
Ok, I don't know how to ask this.
So this is the function. I want to find the gradient of the function for any value of d. So how do I implement this as a function file? Thank you. i will vary from 1 to d.
Star Strider
Star Strider 2018-9-29
One possibility:
function [fsum,delf] = sumsq(xx)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUM SQUARES FUNCTION
%
% INPUT:
%
% xx = [x1, x2, ..., xd]
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cfs = (1:numel(xx)) % Coefficient Vector
f = (xx.^2).*cfs % Calculate ‘f’
delf = xx .* (cfs*2) % Calculate Gradient
fsum = sum(f) % Calculate Sum Of ‘f’
end
I simply wrapped my code in the function code you used.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by