How to write a .csv file from a 1x2 cell?

1 vue (au cours des 30 derniers jours)
Ivan Mich
Ivan Mich le 21 Avr 2020
Commenté : Ivan Mich le 22 Avr 2020
Hello,
In my code I have MI={a b}, where a, b are numbers calculated by equations. MI is 1x2 cell. I would like to write MI to a csv file, But I do not know how.
Could you help me?

Réponse acceptée

Kojiro Saito
Kojiro Saito le 22 Avr 2020
This document is helpful for undestanding exporting cell array to csv files.
If you're using R2019a or later, writecell is the easiest way.
writecell(MI, 'result.csv')
If you want to add variable names (a and b) to the header of csv file, writetable is suitable.
MIt = table(a, b);
writetable(MIt, 'result.csv')
writetable is available from R2013b.
If you're using older version, fopen and fprintf are available.
MI={a b};
fileId = fopen('result.csv', 'w');
formatSpec = '%f, %f\n';
[nrows, ncols] = size(MI);
for row = 1:nrows
fprintf(fileId, formatSpec, MI{row,:});
end
fclose(fileId);
  3 commentaires
Kojiro Saito
Kojiro Saito le 22 Avr 2020
You can write csv files in a for loop. Here is a sample which reads data*.csv and writes result*.csv files.
In this sample, it assumes data1.csv, data2.csv, ... have columns whos names are col1 and col2, then calculate a and b. Please replace the codes so that fit your actual codes.
list = dir('data*.csv');
for n=1:length(list)
t = readtable(list(n).name);
a = mean(t.col1);
b = mean(t.col2);
t2 = table(a, b);
filename = sprintf("result%d.csv", n);
writetable(t2, filename)
end
Or, you can do the same thing by datastore.
ds = datastore('data*.csv');
ds.ReadSize = 'file';
iter = 1;
while hasdata(ds)
t = read(ds);
a = mean(t.col1);
b = mean(t.col2);
t2 = table(a, b);
filename = sprintf("result%d.csv", iter);
writetable(t2, filename)
iter = iter + 1;
end
Ivan Mich
Ivan Mich le 22 Avr 2020
Thank you very much !!!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Performance and Memory dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by