Input and Output in MATLAB

In this section, we summarise how to input and output data from within a program. The format function, which allows us to change the number of decimal places used to display data, is also introduced.

Output

MATLAB automatically echos any output to the screen. This is normally suppressed using a semi-colon (;) after each command line. Consider the following program

 b = 2;         % Assign value to b
 c = 2*b^2;     % Calculates value of c
 a = [b c];     % Matrix of b and c
 a              % Display the output to the screen

The above program gives:
 a =
   2  8
Occasionally it is desirable just to display the output (rather than the a =). This is done using the disp function:
 disp('The meaningless vector A has the values');
 disp(a);
Then the output is written
The meaningless vector A has the values
  2 8

Formats

In many cases, it is desirable for the programmer to have some control over how the output appears. For example it may be desirable to change the number of decimal places displayed, this is done using the format statement. The main variations on this function are listed below:

The use of the format function is illustrated in the following program
 format long
 a =24.4545;
 disp(a);
Then the output is written
24.45450000000000

Input

Rather than assigning values within a program it is often necessary to allow the program user to specify the value(s) assigned to a given variable. The input function allows us to read data from a user directly (typing at the keyboard):

 Pressure = input('Please enter a single value for the system pressure') 
will wait for the user to type in a value for the variable Pressure.

Save

To store variables to a file the save command is used. The command

 save fname 
stores all the variable existing in the workspace into a file called fname.mat . To save only one or a selection of variables list the variable names after the filename e.g
 save fname a b 
A .mat file is a binary file that can generally only be read by MATLAB. If you wish to store the data in ASCII format so that it can be read by other programs such as NOTEPAD and MS EXCEL, then the save command becomes
 save fname a b -ascii 

Load

To load a standard .mat file created using the save statement above we use the load function.

 load fname 
This will load all the variables from the binary file fname.mat with their original names as saved.

The command

 load fname.???
will load data from the ASCII or text file called fname.??? . If the data is given on m rows and n columns the result will be a m-by-n matrix called fname .

For example if we have a file called jmdata.txt containing the following data

1.004 2.3434
4.555 23232.23
then using the following command:
load jmdata.txt
we get a 2-by-2 matrix called jmdata.

Click HERE to return to the table of contents.