Find numerical gradient of a function
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
Star Strider
il 29 Set 2018
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 Commenti
Star Strider
il 29 Set 2018
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.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
