Saving Cell array and String to text file.

55 ビュー (過去 30 日間)
pr
pr 2015 年 3 月 30 日
I have a cell_in (combination of numeric, date&time & text data) of size mxn and need to save data in a text file.
Here is the code I have written and it works fine
fid = fopen(FilePath,'w');
for rows = 1:size(Cell_in,1)
fprintf(fid,'%s\n',Cell_in{rows,:});
end
fclose(fid)
Instead of doing it in a loop I changed it to string and saved data to text file using the following code
fid = fopen(FilePath,'w');
fprintf(fid,'%s\n',char(Cell_in));
fclose(fid)
and the text file is completely messed up. Am I doing something wrong?
1.If so what did I do wrong?
2. When loading a txt file to MATLAB one can extract the data as cell using
fid = fopen(FileName,'r');
txt_data = textscan(fid,'%s','delimiter','\n');
fclose(fid);
but why not the other way round is possible?

採用された回答

Jan
Jan 2015 年 3 月 30 日
fid = fopen(FilePath,'w');
CT = Cell_in.';
fprintf(fid,'%s\n', CT{:});
fclose(fid)
  2 件のコメント
pr
pr 2015 年 3 月 31 日
編集済み: pr 2015 年 3 月 31 日
@ Jan Simon and Konstantinos Sofos : Thank you for the solutions.
Hamdullah Livaoglu
Hamdullah Livaoglu 2018 年 6 月 4 日
Thanks Jan we owe you big gratitudes:) Howeverit doesnt work in loop like this: fprintf(fid,'%5.4f %5.0f %5.2f %5.0f %5.0f %5.2f %s\n',[kappa;R;snr;fik;fek;cor;date{:}]); all variables are doubles except date. it gives:"Error using vertcat Dimensions of matrices being concatenated are not consistent." how can i handle this error?,

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

その他の回答 (2 件)

Konstantinos Sofos
Konstantinos Sofos 2015 年 3 月 30 日
編集済み: Konstantinos Sofos 2015 年 3 月 30 日
Hi,
Can you try
fid = fopen(FilePath,'w');
fprintf(fid,'%s\n',cellfun(@(x) char(x),Cell_in,'UniformOutput',false));
fclose(fid)
or
fid = fopen(FilePath,'w');
fprintf(fid,'%s\n',char(cellfun(@(x) char(x),Cell_in,'UniformOutput',false)));
fclose(fid)
or you can convert to table and then export if you use R2013b or later
Regards,

Simon Wiedemann
Simon Wiedemann 2017 年 9 月 4 日
Hello there,
i have a problem with writing many files.
There are some (~20) Text-Files with strings of different lenght. I need to copy these files multiple times and change 1-5 lines in the copied files.
Till now i load a File in a cell array, change the lines and write them back to a new file with function fprintf. This is very slow so it takes very long to do this for every file.
Is it possible to copy a file and then only change one line in the already stored file? And would that be faster? Or is a other faster way?
Best regards, Simon

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by