From 3aeb1ff7e38e93c0f248b77567189e5d4cfbef0d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Adjemian=20=28Charybdis=29?=
 <stepan@adjemian.eu>
Date: Thu, 24 Nov 2022 16:22:48 +0100
Subject: [PATCH] Fix pac.estimate.iterate_ols.

Was crashing if the auxiliary model contains a constant.

See https://forum.dynare.org/t/iterative-ols-for-pac-equation/21379.
---
 matlab/+pac/+estimate/iterative_ols.m | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/matlab/+pac/+estimate/iterative_ols.m b/matlab/+pac/+estimate/iterative_ols.m
index 3b48b66452..cbf5655fe4 100644
--- a/matlab/+pac/+estimate/iterative_ols.m
+++ b/matlab/+pac/+estimate/iterative_ols.m
@@ -120,21 +120,32 @@ end
 % Build PAC expectation matrix expression.
 dataForPACExpectation = dseries();
 listofvariables = {};
+isconstant = false;
 for i=1:length(M_.pac.(pacmodl).h_param_indices)
     match = regexp(rhs, sprintf('(?<var>((\\w*)|\\w*\\(-1\\)))\\*%s', M_.param_names{M_.pac.(pacmodl).h_param_indices(i)}), 'names');
     if isempty(match)
         match = regexp(rhs, sprintf('%s\\*(?<var>((\\w*\\(-1\\))|(\\w*)))', M_.param_names{M_.pac.(pacmodl).h_param_indices(i)}), 'names');
     end
-    if isempty(strfind(match.var, '(-1)'))
-        listofvariables{i} = match.var;
-        dataForPACExpectation = [dataForPACExpectation, data{listofvariables{i}}];
+    if ~isempty(match)
+        if isempty(strfind(match.var, '(-1)'))
+            listofvariables{end+1} = match.var;
+            dataForPACExpectation = [dataForPACExpectation, data{listofvariables{i}}];
+        else
+            listofvariables{end+1} = match.var(1:end-4);
+            dataForPACExpectation = [dataForPACExpectation, data{match.var(1:end-4)}.lag(1)];
+        end
     else
-        listofvariables{i} = match.var(1:end-4);
-        dataForPACExpectation = [dataForPACExpectation, data{match.var(1:end-4)}.lag(1)];
+        if strcmp(M_.param_names{M_.pac.(pacmodl).h_param_indices(i)}, sprintf('h_%s_constant', pacmodl))
+            isconstant = true;
+        end
     end
 end
+
 dataPAC = dataForPACExpectation{listofvariables{:}}(range).data;
 
+if isconstant
+    dataPAC = [ones(rows(dataPAC),1), dataPAC];
+end
 
 % Build data for non optimizing behaviour
 if is_non_optimizing_agents
-- 
GitLab