Index issue while using gradient of a function
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2020-11-4
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!