Find numerical gradient of a function

2 views (last 30 days)
Tusar Jit Medhi
Tusar Jit Medhi on 29 Sep 2018
Commented: Star Strider on 29 Sep 2018
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

Answers (1)

Star Strider
Star Strider on 29 Sep 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 Comments
Tusar Jit Medhi
Tusar Jit Medhi on 29 Sep 2018
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 on 29 Sep 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.

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!