%% Export Cell Array to Text File
%% Export Cell Array Using fprintf
% This example shows how to export a cell array to a text file, using the fprintf function.
% Create a sample cell array, C, for exporting.

C = {'Atkins',32,77.3,'M';'Cheng',30,99.8,'F';'Lam',31,80.2,'M'}

%
% Open a file named celldata.dat for writing.

fileID = fopen('celldata.dat','w');

% fopen returns a file identifier, fileID, that fprintf calls to write to the file.
%
% Describe the pattern of the file data using format specifiers. Typical format specifiers include '%s' for a character vector, '%d' for an integer, or '%f' for a floating-point number. Separate each format specifier with a space to indicate a space delimiter for the output file. Include a newline character at the end of each row of data ('\n').

formatSpec = '%s %d %2.1f %s\n';

% Some Windows® text editors, including Microsoft® Notepad, require a newline character sequence of '\r\n' instead of '\n'. However, '\n' is sufficient for Microsoft Word or WordPad.
%
% Determine the size of C. Then, export one row of data at a time using the fprintf function.

[nrows,ncols] = size(C);
for row = 1:nrows
    fprintf(fileID,formatSpec,C{row,:});
end

% fprintf writes a space-delimited file.
%
% Close the file.

fclose(fileID);

%
% View the file.

type celldata.dat

%
%% Convert Cell Array to Table for Export
% This example shows how to convert a cell array of mixed text and numeric data to a table before writing the data to a text file. Tables are suitable for column-oriented or tabular data. You then can write the table to a text file using the writetable function.
% Convert the cell array, C, from the previous example, to a table using the cell2table function. Add variable names to each column of data using the VariableNames name-value pair argument.

T = cell2table(C,'VariableNames',{'Name','Age','Result','Gender'});

%
% Write table T to a text file.

writetable(T,'tabledata.dat')

%
% View the file.

type tabledata.dat

% Copyright 2012 The MathWorks, Inc.