Print cell array as .txt in matlab

I have an array of cells that I need to print in a TXT file according to a specific format. I tried part of the online help (including matlab central dlmcell , but even this does not give 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 the tab delimiter)

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

A cell will have a minimum of 8000 rows and a maximum of 15000. No rows would have empty columns. Is it possible to use a vectorized solution? I will get your help.

+4
source share
2 answers

In your example, the following will work:

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

MATLAB reuses the format string until the input ends. Basically, you can first build a format string:

 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); 
+7
source

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

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

Note that in an OS where COM is not available (for example, Linux), XLSWRITE writes text, so you do not need a DLMWRITE call.


UPDATE

This method no longer works with the latest versions of MATLAB (since probably R2012b). xlswrite always writes the file in Excel format.

However, since R2013b MATLAB introduced TABLES and WRITETABLE works fine if the array of cells can be converted to a table (check CELL2TABLE ).

+3
source

Source: https://habr.com/ru/post/1387075/


All Articles