How to Use fscanf in MATLAB: Syntax and Examples
In MATLAB,
fscanf reads formatted data from a file opened with fopen. You specify the file identifier, format string, and optionally the size of data to read. It returns the data as an array or matrix based on the format and size.Syntax
The basic syntax of fscanf is:
A = fscanf(fileID, formatSpec): Reads data from the file with identifierfileIDusing the formatformatSpec.A = fscanf(fileID, formatSpec, sizeA): Reads data up tosizeAelements or matrix size.
Explanation:
fileID: The file identifier fromfopen.formatSpec: A string specifying the data format, e.g.,'%f'for floating-point numbers.sizeA: Optional. Number of elements or a two-element vector for matrix size.
matlab
A = fscanf(fileID, formatSpec) A = fscanf(fileID, formatSpec, sizeA)
Example
This example shows how to read numbers from a text file using fscanf. It opens a file, reads floating-point numbers, and closes the file.
matlab
fileID = fopen('data.txt', 'r'); % Suppose data.txt contains: 10 20 30 40 50 A = fscanf(fileID, '%f'); fclose(fileID); A
Output
A =
10
20
30
40
50
Common Pitfalls
Common mistakes when using fscanf include:
- Not opening the file before reading, causing errors.
- Using incorrect
formatSpecthat does not match file data. - Forgetting to close the file with
fclose, which can lock the file. - Misunderstanding
sizeAparameter, leading to incomplete or excess data reads.
Example of wrong and right usage:
matlab
% Wrong: fscanf without fopen % A = fscanf('data.txt', '%f'); % This causes error % Right: fileID = fopen('data.txt', 'r'); A = fscanf(fileID, '%f'); fclose(fileID);
Quick Reference
| Parameter | Description |
|---|---|
| fileID | File identifier from fopen |
| formatSpec | Format string like '%f', '%d', '%s' |
| sizeA | Optional size of data to read (number or [rows cols]) |
| Return | Array or matrix of data read from file |
Key Takeaways
Always open the file with fopen before using fscanf.
Use the correct format string to match the data type in the file.
Close the file with fclose to free system resources.
Specify size to control how much data fscanf reads.
fscanf returns data as a column vector or matrix depending on size.