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

3 views (last 30 days)
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?

Accepted Answer

Kojiro Saito
Kojiro Saito on 22 Apr 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 Comments
Kojiro Saito
Kojiro Saito on 22 Apr 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

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!