Department of Engineering

IT Services

Input and output

Data can be be transferred to and from MATLAB in four ways:

  • Into MATLAB by running a .m file
  • Loading and saving .mat files
  • Loading and saving data files
  • Using specialised file I/O commands in MATLAB

The first of this involves creating a .m file which contains matrix specifications e.g. if mydata.m contains:


data = [1 1;2 4;3 9;4 16;5 25;6 36];

Then typing:


>> mydata

will enter the matrix data into MATLAB. Plot the results (using the cursor controls, it is possible to edit previous lines):


>> handout_length = data(:,1);

>> boredom = data(:,2);
>> plot(handout_length,boredom);
>> plot(handout_length,boredom,'*');
>> plot(handout_length,boredom,'g.',handout_length,boredom,'ro');

A .mat file can be created by a save command in a MATLAB session (see below).

Data can be output into ASCII (human readable) or non-ASCII form:


>> save results.dat handout_length boredom -ascii

>> save banana.peel handout_length boredom

The first of these saves the named matrices in file results.dat (in your current directory) in ASCII form one after another. The second saves the matrices in file banana.peel in non-ASCII form with additional information such as the name of the matrices saved. Both these files can be loaded into MATLAB using load :


>> clear

>> load banana.peel -mat
>> whos
>> clear
>> load results.dat
>> results
>> apple=reshape(results,6,2)

The clear command clears all variables in MATLAB. The mat option in load interprets the file as a non-ASCII file. reshape allows you to change the shape of a matrix. Using save on its own saves the current workspace in matlab.mat and load on its own can retrieve it.

MATLAB has file I/O commands (much like those of C) which allow you to read many data file formats into it. Create file alpha.dat with ABCD as its only contents. Then:


>> fid=fopen('alpha.dat','r');

>> a=fread(fid,'uchar',0)+4;
>> fclose(fid);
>> fid=fopen('beta.dat','w');
>> fwrite(fid,a,'uchar');
>> fclose(fid);
>> !cat beta.dat

Here, alpha.dat is opened for reading and a is filled with unsigned character versions of the data in the file with 4 added on to their value. beta.dat is then opened for writing and the contents of a are written as unsigned characters to it. Finally the contents of this file are displayed by calling the Unix command cat (the '!' command escapes from matlab into unix).


>> help fopen

>> help fread

will provide more information on this MATLAB facility.