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
0 个评论
回答(1 个)
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 个评论
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
