How to Write File in MATLAB: Syntax and Examples
In MATLAB, you can write data to a file using
fprintf for formatted text or writematrix for numeric arrays. First, open a file with fopen, write data, then close it with fclose to save changes.Syntax
Here are common ways to write files in MATLAB:
fid = fopen(filename, permission): Opens a file. Use 'w' to write (overwrite) or 'a' to append.fprintf(fid, formatSpec, data): Writes formatted text to the file.fclose(fid): Closes the file to save changes.writematrix(data, filename): Writes numeric arrays directly to a file (CSV or text).
matlab
fid = fopen('file.txt', 'w'); fprintf(fid, 'Hello %s!\n', 'world'); fclose(fid); writematrix([1 2; 3 4], 'data.csv');
Example
This example writes a greeting message to a text file and saves a numeric matrix to a CSV file.
matlab
filename = 'greeting.txt'; fid = fopen(filename, 'w'); if fid == -1 error('Cannot open file for writing'); end fprintf(fid, 'Hello, MATLAB user!\nToday is %s.\n', datestr(now, 'dddd')); fclose(fid); matrix = [10 20 30; 40 50 60]; writematrix(matrix, 'numbers.csv');
Common Pitfalls
Common mistakes when writing files in MATLAB include:
- Not checking if
fopensucceeded (returns -1 if failed). - Forgetting to
fclosethe file, which can cause data loss. - Using wrong file permissions (e.g., 'r' for reading only).
- Mixing data types without proper formatting in
fprintf.
matlab
%% Wrong way: forgetting to close file fid = fopen('test.txt', 'w'); fprintf(fid, 'Data without closing file'); % fclose(fid); % Missing fclose can cause issues %% Right way: fclose(fid);
Quick Reference
| Function | Purpose | Example Usage |
|---|---|---|
| fopen | Open file for writing or appending | fid = fopen('file.txt', 'w'); |
| fprintf | Write formatted text to file | fprintf(fid, 'Value: %d\n', 10); |
| fclose | Close the file | fclose(fid); |
| writematrix | Write numeric matrix to file | writematrix([1 2; 3 4], 'data.csv'); |
Key Takeaways
Always open files with fopen and close them with fclose to save data properly.
Use fprintf for writing formatted text and writematrix for numeric arrays.
Check if fopen returns -1 to handle file opening errors.
Forgetting fclose can cause incomplete file writes or data loss.
Choose the correct file permission ('w' to write, 'a' to append).