From b652b6d9320b744ca35bbc12d75a3ab0db8053e2 Mon Sep 17 00:00:00 2001
From: Johannes Pfeifer <jpfeifer@gmx.de>
Date: Thu, 21 Jan 2021 19:33:30 +0100
Subject: [PATCH] csminwel1.m: two small fixes

- gh always exists, no need to check
- allow having non-bad gradient in first iteration
---
 matlab/optimization/csminwel1.m | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)

diff --git a/matlab/optimization/csminwel1.m b/matlab/optimization/csminwel1.m
index 1f67fcb96b..9cc6cddc2e 100644
--- a/matlab/optimization/csminwel1.m
+++ b/matlab/optimization/csminwel1.m
@@ -228,16 +228,16 @@ while ~done
         f2=f;f3=f;f1=f;retcode2=retcode1;retcode3=retcode1;
     end
     %how to pick gh and xh
-    if f3 < f - crit && badg3==0 && f3 < f2 && f3 < f1
+    if f3 < f - crit && badg3==0 && f3 < f2 && f3 < f1  %f3 has improved function, gradient is good and it is smaller than the other two
         ih=3;
         fh=f3;xh=x3;gh=g3;badgh=badg3;retcodeh=retcode3;
-    elseif f2 < f - crit && badg2==0 && f2 < f1
+    elseif f2 < f - crit && badg2==0 && f2 < f1         %f2 has improved function, gradient is good and it is smaller than f2
         ih=2;
         fh=f2;xh=x2;gh=g2;badgh=badg2;retcodeh=retcode2;
-    elseif f1 < f - crit && badg1==0
+    elseif f1 < f - crit && badg1==0                    %f1 has improved function, gradient is good
         ih=1;
         fh=f1;xh=x1;gh=g1;badgh=badg1;retcodeh=retcode1;
-    else
+    else                                                % stuck or bad gradient
         [fh,ih] = min([f1,f2,f3]);
         %disp_verbose(sprintf('ih = %d',ih))
         %eval(['xh=x' num2str(ih) ';'])
@@ -253,12 +253,10 @@ while ~done
             %eval(['retcodeh=retcode' num2str(ih) ';'])
         retcodei=[retcode1,retcode2,retcode3];
         retcodeh=retcodei(ih);
-        if exist('gh')
-            nogh=isempty(gh);
-        else
-            nogh=1;
-        end
-        if nogh
+        
+        nogh=isempty(gh);        
+        badgh=1;
+        if nogh %recompute gradient
             if NumGrad
                 [gh, badgh]=get_num_grad(method,fcn,penalty,fh,xh,epsilon,varargin{:});
             elseif grad_fun_provided
@@ -268,7 +266,6 @@ while ~done
                 badgh = ~cost_flag;
             end
         end
-        badgh=1;
     end
     %end of picking
     stuck = (abs(fh-f) < crit);
-- 
GitLab