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

2 visualizaciones (últimos 30 días)
Ivan Mich
Ivan Mich el 21 de Abr. de 2020
Comentada: Ivan Mich el 22 de Abr. de 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?

Respuesta aceptada

Kojiro Saito
Kojiro Saito el 22 de Abr. de 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 comentarios
Kojiro Saito
Kojiro Saito el 22 de Abr. de 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 el 22 de Abr. de 2020
Thank you very much !!!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Performance and Memory en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by