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

3 次查看(过去 30 天)
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?

采纳的回答

Kojiro Saito
Kojiro Saito 2020-4-22
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 个评论
Kojiro Saito
Kojiro Saito 2020-4-22
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by