Creating a vector of tables

9 vues (au cours des 30 derniers jours)
Calum Henderson
Calum Henderson le 7 Oct 2020
Commenté : madhan ravi le 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 commentaire
Stephen23
Stephen23 le 7 Oct 2020
Modifié(e) : Stephen23 le 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:

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 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 commentaires
Ameer Hamza
Ameer Hamza le 8 Oct 2020
I am glad to be of help!
madhan ravi
madhan ravi le 8 Oct 2020
Naming a variable table will shadow the inbuilt function.

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by