From 581c420f7b4ee1ed2c3001b47120c3729852e056 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Adjemian=20=28Argos=29?=
 <stepan@adjemian.eu>
Date: Mon, 5 Jun 2023 11:10:59 +0200
Subject: [PATCH] Add new method returning last observed period for each
 variable.

---
 src/@dseries/lastobservedperiods.m | 57 ++++++++++++++++++++++++++++++
 src/@dseries/subsref.m             |  1 +
 2 files changed, 58 insertions(+)
 create mode 100644 src/@dseries/lastobservedperiods.m

diff --git a/src/@dseries/lastobservedperiods.m b/src/@dseries/lastobservedperiods.m
new file mode 100644
index 0000000..1a45036
--- /dev/null
+++ b/src/@dseries/lastobservedperiods.m
@@ -0,0 +1,57 @@
+function b = lastobservedperiods(o)
+
+% Return, for each variable, the last period without missing observations (last period without NaN).
+%
+% INPUTS
+% - o   [dseries]    with N variables and T periods.
+%
+% OUTPUTS
+% - b   [struct]     with N fields, each name field is a variable name and its content a date object.
+
+% Copyright © 2023 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
+
+d = cumprod(~isnan(o));
+b = struct();
+
+for i=1:o.vobs
+    b.(o.name{i}) = o.dates(find(d(:,i), 1, 'last'));
+end
+
+return % --*-- Unit tests --*--
+
+%@test:1
+try
+    a = randn(10, 3);
+    a(end,1) = NaN;
+    a(end,2) = NaN;
+    a(end-1,2) = NaN;
+    A = dseries(a, '2000Q1', {'A1', 'A2', 'A3'});
+    b = A.lastobservedperiods();
+    t(1) = true;
+catch
+    t(1) = false;
+end
+
+if t(1)
+    t(2) = isequal(b.A1, dates('2002Q1'));
+    t(3) = isequal(b.A2, dates('2001Q4'));
+    t(4) = isequal(b.A3, dates('2002Q2'));
+end
+
+T = all(t);
+%@eof:1
diff --git a/src/@dseries/subsref.m b/src/@dseries/subsref.m
index 5f72f86..74b0820 100644
--- a/src/@dseries/subsref.m
+++ b/src/@dseries/subsref.m
@@ -129,6 +129,7 @@ switch S(1).type
             'lastdate', ...
             'firstobservedperiod', ...
             'lastobservedperiod', ...
+            'lastobservedperiods', ...
             'lineartrend', ...
             'resetops', 'resettags', ...
             'subsample', ...
-- 
GitLab