Reading and writing data lets your program get information from files and save results. This is how programs talk to the outside world.
0
0
Why reading and writing data is fundamental in MATLAB
Introduction
You want to load a list of numbers from a file to analyze them.
You need to save your program's results so you can use them later.
You want to read text data like names or messages from a file.
You want to write logs to keep track of what your program did.
You want to share data between different programs or users.
Syntax
MATLAB
fileID = fopen('filename.ext', 'mode'); data = fread(fileID); fclose(fileID); fileID = fopen('filename.ext', 'mode'); fwrite(fileID, data); fclose(fileID);
fopen opens a file. The 'mode' can be 'r' for reading or 'w' for writing.
fclose closes the file to save changes and free resources.
Examples
This reads all data from 'data.txt' as bytes.
MATLAB
fileID = fopen('data.txt', 'r'); data = fread(fileID); fclose(fileID);
This writes the text 'Hello World' into 'output.txt'.
MATLAB
fileID = fopen('output.txt', 'w'); fwrite(fileID, 'Hello World'); fclose(fileID);
This reads the entire text file 'notes.txt' into a string variable.
MATLAB
data = fileread('notes.txt');This writes a matrix of numbers into a CSV file.
MATLAB
writematrix([1 2 3; 4 5 6], 'numbers.csv');
Sample Program
This program writes a short message to a file, then reads it back and shows it on the screen.
MATLAB
filename = 'example.txt'; % Write some text to the file fileID = fopen(filename, 'w'); fprintf(fileID, 'Hello, MATLAB!\nThis is a test file.'); fclose(fileID); % Read the text back from the file fileID = fopen(filename, 'r'); textData = fscanf(fileID, '%c'); fclose(fileID); % Display the read text fprintf('Content of the file:\n%s\n', textData);
OutputSuccess
Important Notes
Always close files after opening them to avoid errors and data loss.
Use the right mode ('r' for reading, 'w' for writing) to avoid overwriting or reading errors.
Reading and writing lets your program save work and use data from outside sources.
Summary
Reading and writing data connects your program to files and the outside world.
You use fopen, fread, fwrite, and fclose to handle files.
This lets you save results, load inputs, and share information easily.