How can I combine multiple matfile containing row vector in one table
Show older comments
I have several dot matfile containing row vector and I want them to put in one table sequentially (according to alphabetic order of the file name).
I tried the following script which I found in Math works, it combines all the files in one table, however when I use it for more number files it do not work sequentially and I faced difficulty to identify which row corresponds to which file.
clear
FileList = dir('As*.mat');
DataC = cell(1, numel(FileList));
for iFile = 1:numel(FileList)
FileData = load(FileList(iFile).name);
DataC{iFile} = FileData.X;
end
DataM = cat(1, DataC{:});
I have attached sample dot mat files
Thank You for response
7 Comments
Nikhil Sapre
on 25 Jun 2021
Edited: Nikhil Sapre
on 25 Jun 2021
Hi Yared,
Can you check if the order is correct in the variable FileList. My guess is the problem happens because the sorted order would be As(1), As(10), As(2) etc .. when using the dir function
A workaround would be to name your file As(01), As(02), As(03) and so on. This should fix the order.
Thanks,
Nikhil
Yared Daniel
on 25 Jun 2021
Nikhil Sapre
on 25 Jun 2021
You don't need to rename the files. You can sort it based on date created. Here's a snippet of code how to do this in your case. This is assuming your files were created in the order they are named.
FileList = dir('As*.mat');
DataC = cell(1, numel(FileList));
[~,idx] = sort([FileList.datenum]);
for iFile = 1:numel(idx)
FileData = load(FileList(idx(iFile)).name);
DataC{iFile} = FileData.X;
end
DataM = cat(1, DataC{:});
Yared Daniel
on 25 Jun 2021
Edited: Yared Daniel
on 26 Jun 2021
Nikhil Sapre
on 25 Jun 2021
Done, thanks
A more robust solution that does not assume that the files were created/modified in the filename order:
For example:
P = 'absolute or relative path to where the files are saved';
S = dir(fullfile(P,'As*.mat'));
S = natsortfiles(S);
for k = 1:numel(S)
F = fullfile(P,S(k).name);
D = load(F);
S(k).X = D.X;
end
DataM = cat(1, S.X);
Nikhil Sapre
on 26 Jun 2021
Thanks. This is a better solution. I didn't know of the natsortfile function.
Accepted Answer
More Answers (0)
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!