Creating a vector of tables
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2020-10-7
编辑:Stephen23
2020-10-7
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:
采纳的回答
Ameer Hamza
2020-10-7
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!