Matlab IO
Contents
Input in MATLAB
Input can be accomplished in several ways in Matlab:
- Interactive input from the user. This is accomplished using the input command.
- Reading files from disk. There are two common methods to do this: using fscanf command and using the load command.
The INPUT command
The basic syntax for the input command is:
x = input('Enter the value of x: ');
|
This outputs the given text to the command window. The user can then enter a value and it will be stored in x.
Loading variables using LOAD
|
The FSCANF command
There are three steps to read from a file:
- Open the file using fopen
- Read from the file using fscanf
- Close the file using fclose
The fscanf command is used primarily for reading from files. The basic syntax is:
value = fscanf( fid, format, size );
| ||||||||||||||
|
Opening and Closing Files
Before reading from a file, we must open it. This is done using the fopen command:
fid = fopen('filename','r'); % opens a file named "filename" for reading.
|
This assigns an identifier to fid that can be used in subsequent file operations (reading, closing, etc.). The 'r' indicates that this file is to be read from. Options are:
Flag | Description |
---|---|
'r' | Open a file for reading. |
'w' | Open a file for writing (creates the file if it doesn't already exist). An existing file will be overwritten. |
'a' | Open a file and append it (creates the file if it doesn't already exist). |
After you are done with a file, you should close it using the fclose command:
fclose(fid); % closes the file referred to be "fid"
|
A Simple Example
File "ages.dat" | Matlab Commands | Explanation |
---|---|---|
Fred 64 Bob 32 Julia 49 |
file = fopen('ages.dat','r');
name = fscanf( file, '%s', 1 );
age = fscanf( file, '%s' );
fclose(file);
|
Reads a string number into the variable name. Note the "1" at the end of this statement. If we didn't use "1" when reading the name, then it would have read the entire file into the string. After reading the name, we read the age into the variable age. |
If we wanted to read the whole file, we would need a few additional things:
- A cell array to hold the names
- An array to hold the ages.
- A way to determine when we hit the end of the file. This is done using the feof(fid) command.
Using these concepts, we can now read the file.
fid = fopen('ages.dat','r'); % opens the file "ages.dat" for reading.
i = 1;
names = {};
ages = [];
while ~feof(fid)
names{i} = fscanf(fid,'%s',1); % read the name.
age(i) = fscanf(fid,'%i'); % read the age.
i = i+1; % get ready to read the next line
end
fclose(fid); % close the file.
|
Terminal and File Output in MATLAB
|
DISP
FPRINTF
File Output
Saving Variables with SAVE
Exporting Matlab Figures
|