1
votes

I am using Matlab 2019 and I saved a large number of different tables with the same name, each in a .mat-file with a different name. I'd like to load them and save them in a new table together.

I need a table that has the same variables (variable1, variable2, variable3), and numbers but an additional dimension for the different .mat-files. I.e. in the dummy code below the size of the table allData should be: 2 x 3 x 2.

If I simply concatenate them like this [Results1.Inpts; Results2.Inpts], then the table is 4 x 3 and I cannot distinguish the data from the different files.

Also I have a large number of .mat-files, so I would like to automate it like done here (https://www.mathworks.com/matlabcentral/answers/233745-loading-mat-files-with-same-variable-name), which I tried to do for my table below, but it didn't work.

Please find my dummy code below.

%% Create data and .mat files

clc;
clear;
close all;
format long;

Names = {'variable1','variable2','variable3'};
Numbers1 = [2, 3, 4; 3, 4, 5];
Numbers2 = [1, 4, 10; 2, 6, 3];

Inpts = array2table(Numbers1,'VariableNames',Names);
save('Results1.mat');
clear Inpts;

Inpts = array2table(Numbers2,'VariableNames',Names);
save('Results2.mat');

clear;

%% Analyse data

files = dir('*.mat');
allData = table(size(files));
for ii=1:length(files)
  aFileData = load(files(ii).name);
  allData{ii} = aFileData.Inpts;
end
2

2 Answers

2
votes

I think you just need to add a column in each table before concatenation

allData = cell(numel(files),1); % Store the tables in a cell
for ii=1:length(files)
  aFileData = load(files(ii).name);
  % Add a column
  aFileData.FileName(:) = {files(ii).name};
  % Stick the modified table in the cell
  allData{ii} = aFileData.Inpts;
end
% Merge tables
allData = vertcat( allData{:} );
1
votes

If you really want to do a 3-dimensional array with the third dimension corresponding to files, you can't use a table, because tables are inherently two-dimensional. Instead, convert your table data back to a matrix after reading it, and then concatenate them along the third dimension.

allData = cell(numel(files), 1);
for i = 1:numel(files)
  fileTable = load(files(i).name);
  fileMat = table2array(fileTable);
  allData{i} = fileMat;
end
data = cat(3, allData{:});