print a cell array as .txt in Matlab

折月煮酒 提交于 2019-12-21 18:30:06

问题


I have a cell array that needs to be printed in a .txt file according to a specific format. I have tried some of the online help (including matlab central dlmcell but even that is not giving me the desired answer. Delimiter is \t.

cellarray = { ...
        'AAPL' '2/20/2011' 100.5 
        'MSFT' '2/15/2011' 43.4551
            } ;

The output should be in a .txt file with the following format: (using tab delimiter)

"AAPL"    "2/20/2011"    100.5
"MSFT"    "2/15/2011"    43.4551

The cell will have minimum of 8000 rows and a maximum of 15000. No rows would have empty columns. Is a vectorized solution possible? Shall appreciate your help.


回答1:


The following will work for your example:

C = cellarray.';
fid = fopen('file.dlm', 'wt');
fprintf(fid, '"%s"\t"%s"\t%g\n', C{:});
fclose(fid);

MATLAB reuses the formatting string until it runs out of inputs. In principle, you could construct the formatting string first:

fstr = '';
for ic = 1:size(cellarray,2)
   switch class(cellarray{1,ic})
       case 'char'
           fstr = [fstr '"%s"'];
       otherwise
           % Assume numeric
           fstr = [fstr '%g'];
   end
   if ic < size(cellarray,2), fstr = [fstr '\t']; else fstr = [fstr '\n']; end
end

Then

C = cellarray.';
fid = fopen('file.dlm', 'wt');
fprintf(fid, fstr, C{:});
fclose(fid);



回答2:


I often use combination of DLMWRITE and XLSWRITE. DLMWRITE is used to make a text file, so XLSWRITE will not generate the file in Excel format, but will leave it as a text.

filename = 'file.txt';
dlmwrite(filename, 1)
xlswrite(filename, cellarray)

Note that on OS where COM is not available (like Linux) XLSWRITE write to text, so you don't need the call to DLMWRITE.


UPDATE

This method does not work anymore with the latest versions of MATLAB (since probably R2012b). xlswrite always writes to Excel-formatted file.

However, since R2013b MATLAB introduced TABLES, and WRITETABLE function works great if cell array can be converted to a table (check CELL2TABLE function).



来源:https://stackoverflow.com/questions/8565617/print-a-cell-array-as-txt-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!