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

1 回表示 (過去 30 日間)
Ivan Mich
Ivan Mich 2020 年 4 月 21 日
コメント済み: Ivan Mich 2020 年 4 月 22 日
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
Ivan Mich
Ivan Mich 2020 年 4 月 22 日
Thank you very much !!!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by