MATLAB - Data Output
MATLAB - Data Output and Export
Section titled “MATLAB - Data Output and Export”Exporting data from MATLAB means writing variables from the workspace into files. This is essential for saving results, sharing data with other applications, or creating reports. Modern MATLAB offers a suite of high-level functions that make data export simple and robust.
Modern High-Level I/O Functions (Recommended)
Section titled “Modern High-Level I/O Functions (Recommended)”For most common data export tasks, you should use the write___ family of functions. These functions are powerful, flexible, and have replaced older functions like dlmwrite.
writematrix: Writes a numeric matrix to a text file.writecell: Writes a cell array to a text file.writetable: Writes atableto a file. This is the most powerful option for mixed-type tabular data (e.g., columns of numbers, text, and dates) and supports formats like.csvand.xlsx.
Example: Using writematrix
Section titled “Example: Using writematrix”Let’s create a numeric matrix and save it to a comma-separated values (CSV) file.
% Create a sample numeric matrixnum_matrix = [1.5, 2.3, 8.1; 4.0, 5.2, 6.9];
% Export the matrix to a CSV fileoutput_filename = 'matrix_data.csv';writematrix(num_matrix, output_filename);
% Verify by displaying the file contentfprintf('File ''%s'' created. Content:\n', output_filename);type(output_filename);The output file matrix_data.csv will contain:
1.5,2.3,8.14,5.2,6.9Example: Using writetable
Section titled “Example: Using writetable”The table data type is excellent for handling data with named columns of different types. writetable automatically includes the column headers in the output file.
% Create a table with mixed data typesLastName = ["Smith"; "Jones"; "Williams"];Age = [38; 29; 45];BloodPressure = [124, 82; 115, 78; 130, 88];
data_table = table(LastName, Age, BloodPressure);
% Export the table to a text file with a tab delimiteroutput_filename = 'patient_data.txt';writetable(data_table, output_filename, 'Delimiter', '\t');
% Verify by displaying the file contentfprintf('\nFile ''%s'' created. Content:\n', output_filename);type(output_filename);The output file patient_data.txt will be neatly formatted:
LastName Age BloodPressure_1 BloodPressure_2"Smith" 38 124 82"Jones" 29 115 78"Williams" 45 130 88Low-Level File I/O for Custom Formats
Section titled “Low-Level File I/O for Custom Formats”When you need complete control over the file format (e.g., creating a structured log file or a custom text format), you can use the low-level I/O functions: fopen, fprintf, and fclose.
Example: Creating a Log Table
Section titled “Example: Creating a Log Table”This example creates a two-column table in a text file, demonstrating robust error handling and file management.
% Prepare datax = 0:10:100;y_data = [x; log(x)];output_filename = 'log_table.txt';
% Open file for writing ('w'). Best practice is to check the file ID.fid = fopen(output_filename, 'w');if fid == -1 error('Cannot open file: %s', output_filename);end
% Use a try-catch block to ensure the file is closed even if errors occurtry % Write a header to the file fprintf(fid, '--- Logarithm Table ---\n'); fprintf(fid, '%-10s | %-15s\n', 'Value', 'Log(Value)'); fprintf(fid, '---------------------------\n');
% Write the data in a loop for precise formatting fprintf(fid, '%-10.2f | %-15.4f\n', y_data);
fprintf('\nFile ''%s'' created successfully.\n', output_filename);catch ME % If an error occurs during writing, close the file and rethrow the error fclose(fid); rethrow(ME);end
% Close the filefclose(fid);
% Display the created filetype(output_filename);The resulting file log_table.txt will look like this:
--- Logarithm Table ---Value | Log(Value)---------------------------0.00 | -Inf10.00 | 2.302620.00 | 2.995730.00 | 3.401240.00 | 3.688950.00 | 3.912060.00 | 4.094370.00 | 4.248580.00 | 4.382090.00 | 4.4998100.00 | 4.6052Other Export Methods
Section titled “Other Export Methods”diary: Creates a log of your MATLAB command window session. Useful for simple record-keeping. Usediary onto start,diary offto stop.savecommand: Primarily used for saving workspace variables to a.matfile (save('my_data.mat')), which is a binary format perfect for reloading into MATLAB later. The-asciioption is considered legacy and less flexible thanwritematrix.
Note on Deprecated Functions: The function dlmwrite is no longer recommended. Use writematrix for its improved performance and features.