Index issue while using gradient of a function
4 views (last 30 days)
Show older comments
Braden Kerr
on 4 Nov 2020
Commented: Braden Kerr
on 4 Nov 2020
Hello,
I am attempting to take the gradient of a function and use that as a varaible in matlab function in order to calculate a specific matrix of values.
I currently am taking the gradient by the following code, where fun is the function I need to take the gradient of:
syms x [1 2]
fun = -9*x(1) -10*x(2) + theta*(-log(100-x(1)-x(2))-log(x(1))-log(x(2)) - log(50-x(1)+x(2)));
grad_fun = gradient(fun, x);
x0 = [8 90]'; % change this for different sub-problems in the homework
choice = 1; % 1 = bisection; 2 = Armijo
[alpha, F, X]= steepestdescent(fun,grad_fun,eps,x0,choice,stp_eps);
I then have another script that I am writing a rather long function within that needs to use the grad_fun at various points, I thus have the following:
function [out1, out2, out3] = steepestdescent(fun,grad_fun,eps,x0,choice,stp_eps)
if choice == 1
X=[]; D=[]; A=[]; F=[];
X(:,1)= x0; %initialize state
D(:,1)= -grad_fun(x0); %initial direction
However, in my debugging process, I keep getting an error when I reach D(:,1) that states
Index exceeds the number of array elements (2).
Error in sym/subsref (line 902)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in steepestdescent (line 7)
D(:,1)= -grad_fun(x0); %initial direction
Error in HW4_3 (line 45)
[alpha, F, X]= steepestdescent(fun,grad_fun,eps,x0,choice,stp_eps);
The last element of the error, where it states Error HW4_3 (line 45) I know is associated with my use of grad_fun in my use of the function at the bottom of the first block of code, but I cant figure out why grad_fun is not returning the proper elements.
The gradient should hopefully take in the function fun, take its gradient, save that symbolic gradeint in a 2x1 matrix, then when the grad_fun function is called, be able to plug in the values for x0 and return a 2x1 matrix of two doubles that can then be stored and used elsewhere in the code.
Let me know if I need to clarify anything, thank you.
0 Comments
Accepted Answer
Walter Roberson
on 4 Nov 2020
grad_fun is a vector not a function. You cannot use () notation to evaluate it, you have to use subs. Or use matlabFunction to turn it into a function handle (and be sure to use the option 'vars',{x} for that)
5 Comments
More Answers (0)
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!