Creating a vector of tables
9 views (last 30 days)
Show older comments
Calum Henderson
on 7 Oct 2020
Commented: madhan ravi
on 8 Oct 2020
I currently have a script that loops through a number of '.csv' files in a directory and creates a table with the data from each file:
directory = dir(dirname);
filenames = {directory(:).name}';
csvfiles = filenames(endsWith(filenames,'.csv'));
for i = 1:length(csvfiles)
file = [char(dirname) '/' char(csvfiles(i))];
CTLdata = readmatrix(file);
table = array2table(CTLdata,...
'VariableNames',{'Current','Voltage','Resistance'});
end
It reads the files correclty, but my issue is that only the final table is saved for use. I would like to produce a "vector of tables" of sorts, and I have tried:
tables(i) = table
among other things but I have had no luck.
What is the best way for me to save the info from each file in a separate table?
1 Comment
Stephen23
on 7 Oct 2020
Edited: Stephen23
on 7 Oct 2020
Rather than getting all directory contents and filtering them afterwards, it is simpler to just get the required files in the first place:
S = dir(fullfile(dirname,'*.csv'));
csvfiles = {S.name};
You should be using fullfile instead of concatenating strings together (I fixed the cell indexing too):
file = fullfile(dirname,csvfiles{i});
And the answer to your qusetion is to use a cell array, just the the documentation recommends:
Accepted Answer
Ameer Hamza
on 7 Oct 2020
Tables cannot be combined in a simple array. You need a cell array
directory = dir(dirname);
filenames = {directory(:).name}';
csvfiles = filenames(endsWith(filenames,'.csv'));
tables = cell(size(csvfiles))
for i = 1:length(csvfiles)
file = [char(dirname) '/' char(csvfiles(i))];
CTLdata = readmatrix(file);
table = array2table(CTLdata,...
'VariableNames',{'Current','Voltage','Resistance'});
tables{i} = table;
end
3 Comments
More Answers (0)
See Also
Categories
Find more on Whos 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!