How do I plot the value at each iteration?
    11 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    SA
 el 20 de Mzo. de 2020
  
    
    
    
    
    Comentada: SA
 el 21 de Mzo. de 2020
            My code below is to compute the minimum value and vector using the conjugate gradient method. How do i plot the value at each iteration? Thanks.
%this program computes the optimal solution of a nonlinear programming
%using the conjugate-gradient method
%xstar - the global optimal solution
%value - optimal solution
function[xstar, minv] = conj_grad(Q,x,q,c,n,tol)
tic;
g0 = (0.5*Q'*x) + (0.5*Q*x) + q; %g is the gradient
d = -g0;
b = (-g0) + Q*x;
g_old = g0;
for i = 1:n
    alpha = -(g_old'*d)/(d'*Q*d)
    x = x + (alpha*d)
    g_new = (Q*x) - b
    beta = (g_new'*Q*d)/(d'*Q*d)
    res = norm(g_new) %res = residual which is the min distance
    value = (0.5*x'*Q*x) +(q'*x) + c
    if res < tol
         xstar = x
         minv = value
         fprintf("The minimum value is %d and it converged after %d iterations \n", value, i)
         break
    end
    d = (-g_new) + (beta*d)
    g_old = g_new
end
toc 
end
0 comentarios
Respuesta aceptada
  Cris LaPierre
    
      
 el 20 de Mzo. de 2020
        7 comentarios
  Cris LaPierre
    
      
 el 21 de Mzo. de 2020
				
      Editada: Cris LaPierre
    
      
 el 21 de Mzo. de 2020
  
			This assumes res and value can be plotted on the same axes.
%this program computes the optimal solution of a nonlinear programming
%using the conjugate-gradient method
%xstar - the global optimal solution
%value - optimal solution
function[xstar, minv] = conj_grad(Q,x,q,c,n,tol)
tic;
g0 = (0.5*Q'*x) + (0.5*Q*x) + q; %g is the gradient
d = -g0;
b = (-g0) + Q*x;
g_old = g0;
for i = 1:n
    alpha = -(g_old'*d)/(d'*Q*d)
    x = x + (alpha*d)
    g_new = (Q*x) - b
    beta = (g_new'*Q*d)/(d'*Q*d)
    res = norm(g_new) %res = residual which is the min distance
    value = (0.5*x'*Q*x) +(q'*x) + c
    % Plot res, value
    plot(i,res,'ro',i,value,'gs')
    hold on
    if res < tol
         xstar = x
         minv = value
         fprintf("The minimum value is %d and it converged after %d iterations \n", value, i)
         break
    end
    d = (-g_new) + (beta*d)
    g_old = g_new
end
hold off
toc 
end
Más respuestas (0)
Ver también
Categorías
				Más información sobre Get Started with Problem-Based Optimization and Equations en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

