From f164750a918627833cb0c70c704ba6ec796e8c25 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Wed, 15 Sep 2021 17:37:08 +0200
Subject: [PATCH] Old MATLAB compatibility fix

This is a partial revert of 4346903c65db6404755e207fab0f4e526cccef01. The
xlswrite function is actually not able to write XLS files on GNU/Linux and
macOS, and moreover its CSV fallback does not work with cell arrays.
---
 matlab/+occbin/write_regimes_to_xls.m | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)

diff --git a/matlab/+occbin/write_regimes_to_xls.m b/matlab/+occbin/write_regimes_to_xls.m
index cfe9b793dd..3e8767de9f 100644
--- a/matlab/+occbin/write_regimes_to_xls.m
+++ b/matlab/+occbin/write_regimes_to_xls.m
@@ -52,19 +52,29 @@ else
     end
 end
 
-filename=[OutputDirectoryName filesep xls_filename '.xls'];
+if ~ispc && ~isoctave && matlab_ver_less_than('9.0')
+    % On GNU/Linux and macOS, with MATLAB < R2016a, “writeable” can’t write Excel files
+    % (and “xlswrite” can’t either)
+    warning('This version of MATLAB is too old and cannot create Excel files. The Occbin regimes will rather be written to a CSV file.')
+    filename=[OutputDirectoryName filesep xls_filename '.csv'];
+else
+    filename=[OutputDirectoryName filesep xls_filename '.xls'];
+end
 
 if isfile(filename)
     delete(filename)
 end
 
-if isoctave || (~ispc && matlab_ver_less_than('9.0'))
+if isoctave
     % “writetable” and “array2table” don’t exist under Octave
-    % On GNU/Linux and macOS, with MATLAB < R2016a, “writeable” can’t write Excel files
     if isoctave && ~user_has_octave_forge_package('io')
         error('The io package is required to write XLS files from Octave')
     end
     xlswrite(filename, vertcat(Header, xlsmat));
+elseif  ~ispc && matlab_ver_less_than('9.0')
+    % Use a CSV file. See the comment above about filename.
+    % We don’t use xlswrite because its CSV fallback does not support cell-arrays.
+    writetable(array2table(xlsmat,'VariableNames',Header), filename);
 else
     writetable(array2table(xlsmat,'VariableNames',Header), filename, 'Sheet', 'Regimes');
 end
-- 
GitLab