Creating a vector of tables

8 次查看(过去 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
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
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 个评论
Ameer Hamza
Ameer Hamza 2020-10-8
I am glad to be of help!
madhan ravi
madhan ravi 2020-10-8
Naming a variable table will shadow the inbuilt function.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by