From 380fd84cb32b6ccec833f183f4a9f76de30fe71d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Adjemian=20=28Ry=C3=BBk=29?=
 <stepan@adjemian.eu>
Date: Wed, 1 Sep 2021 10:35:45 +0200
Subject: [PATCH] Fix NLS estimation routine.

Closes #1798
---
 matlab/+estimate/nls.m | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)

diff --git a/matlab/+estimate/nls.m b/matlab/+estimate/nls.m
index be51120202..96009ab7d8 100644
--- a/matlab/+estimate/nls.m
+++ b/matlab/+estimate/nls.m
@@ -136,10 +136,27 @@ else
     end
 end
 
-% Remove residuals from the equation. Note that a plus or minus will
-% remain in the equation, but this seems to be without consequence.
+% Remove residuals from the equation. Note that a plus or minus will remain in the equation
 rhs = regexprep(rhs, rname, '');
 
+% FIXME The JSON output for rhs (with aux variables substitutions) is not always
+% the same regarding to the position of the residual. If the residual appears at
+% the end of the equation, after the removal of rname the rhs will end with a +
+% symbol which will result in a crash later when evaluating the sum of square
+% residuals. If the residual appears at the begining of the equation, after the
+% removal of rname the rhs will begin with a + symbol which is just awful (but
+% will not cause any trouble).
+
+% Remove trailing + (if any, introduced when removing residual)
+if isequal(rhs(end), '+')
+    rhs = rhs(1:end-1);
+end
+
+% Remove leading + (if any, introduced when removing residual)
+if isequal(rhs(1), '+')
+    rhs = rhs(2:end);
+end
+
 %
 % Rewrite and print the equation.
 %
-- 
GitLab