fprintf('iteration %d, value %f\n', [k, fun_val]) printing out wrong value
3 次查看(过去 30 天)
显示 更早的评论
The following code initialized a quadratic function then performs gradient descent
%build function
%--------------------------------------------------------------------------
A = [1, 2; 3 4];
b = [1,2]'
c = [0,0]
f = @(x) 1/2*x'*A*x + b'*x + c
%Gradient Descent
%-------------------------------------------------------------------------
%initialize gradient descent
epsilon = 0.01;
x0 = [1, 1]';
x=x0;
k=0;
grad= A*x + b;
while (norm(grad) > epsilon)
k=k+1;
t= norm(grad)^2/(2*grad'*A*grad);
x=x-t*grad;
grad= A*x+b;
fun_val= f(x);
fprintf('iteration %d, value %f\n', [k, fun_val])
end
However, for some unknown reason, the fprintf is printing the values of "fun_val" as iteration
iteration 1, value 1.447837
iteration 1.447837e+00, value iteration 2, value -0.135126
iteration -1.351264e-01, value iteration 3, value -0.504093
iteration -5.040926e-01, value iteration 4, value -0.584031
iteration -5.840306e-01, value iteration 5, value -0.599152
iteration -5.991521e-01, value iteration 6, value -0.602219
iteration -6.022192e-01, value iteration 7, value -0.609555
iteration -6.095549e-01, value iteration 8, value -0.801859
iteration -8.018594e-01, value iteration 9, value -0.835942
iteration -8.359422e-01, value iteration 10, value -0.848505
iteration -8.485046e-01, value iteration 11, value -0.622973
iteration -6.229734e-01, value iteration 12, value -0.638213
iteration -6.382132e-01, value iteration 13, value -0.684021
iteration -6.840212e-01, value iteration 14, value -0.697310
iteration -6.973100e-01, value iteration 15, value -1.028292
iteration -1.028292e+00, value iteration 16, value -1.093322
iteration -1.093322e+00, value iteration 17, value -1.117833
iteration -1.117833e+00, value iteration 18, value -0.733297
iteration -7.332971e-01, value iteration 19, value -0.803574
I can't seem to figure out how to fix this problem. Can anyone assist?
0 个评论
回答(1 个)
Star Strider
2018-1-21
Your ‘fun_val’ variable is a (1x2) vector. Choose one element of it (or the mean of them or something else), then print that.
Example —
fprintf('iteration %d, value %f\n', [k, fun_val(1)])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with Optimization Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!