Chapter 9: Data In, Data Out

 

Here we are going to show you how to load and save data in three file formats – a native Matlab "mat" file, an Excel spreadsheet and a text file.

 

.mat format

 

Matlab saves data in something called a mat file, which will show up with the extension .mat.

To save variables you simply need to specify the filename you want to save under, and the variables you want to save. If you don't specify which variables you want to save Matlab will save all variables. By default, matlab saves in the current directory.

 

clear all

x=1:10; y=10:-1:1; z=x(1)+y(4);

save mymatfile x y

disp(['variables saved in directory ', pwd])  

 

variables saved in directory C:\Program Files\MATLAB\R2008a  

 

You can reload these variables using the command load.  

 

clear all

who

load mymatfile

who  

 

 

Your variables are:

 

x  y    

 

Here's another way to use save and load. This is useful when the name you want to save your variables under is defined as a Matlab string.

 

filename='mysecondmatfile';

save(filename, 'x');

clear all

who  

 

filename='mysecondmatfile';

load(filename);

who  

 

 

Your variables are:

 

filename  x           

 

You can also specify which variable you want to load from a mat file. Here, we specifying that we only want to load the variable y.

clear all

load mymatfile y

who  

 

 

Your variables are:

 

y    

 

Reading in and out of Excel

Here's some example code MatlabExcelFile.m showing how to write and read data into Excel.

 

% MatlabExcelFile.m

%

% Example of how to read and write data into Excel

 

clear all

xlsfilename='MatlabExcelFile.xls';

for d=1:4

    sheetname=['Day ', num2str(d)];

xlswrite(xlsfilename, {'Subject', 'Resp 1', 'Resp2', 'Resp3'}, sheetname, 'a1:d1')

   xlswrite(xlsfilename, [1:18]', sheetname, 'a2:a19');

   xlswrite(xlsfilename, rand(18, 3), sheetname, 'b2:d19');

end

disp(['Excel spreadsheet created in ', pwd]);  

 

Warning: Added specified worksheet.

> In xlswrite>activate_sheet at 269

  In xlswrite at 228

Warning: Added specified worksheet.

> In xlswrite>activate_sheet at 269

  In xlswrite at 228

Warning: Could not start Excel server for export.

XLSWRITE will attempt to write file in CSV format.

> In xlswrite at 166

Warning: Added specified worksheet.

> In xlswrite>activate_sheet at 269

  In xlswrite at 228

Warning: Added specified worksheet.

> In xlswrite>activate_sheet at 269

  In xlswrite at 228

Excel spreadsheet created in C:\Program Files\MATLAB\R2008a  

 

The first argument to xlswrite is the name of the Excel file you want to write into (or create and write into), the second argument is the data you want to write, the third (optional) argument is the same of the Excel worksheet you want to write into and the last argument is a list of the cells into which the data should be written. You should now be able to find a file called MatlabExcelFile.xls which contains that data.

 

BEWARE – xlswrite willl quite happily write over data. When dealing with real data, make sure you have backed it up.

 

Now let's read Excel data into Matlab using xlsread.

 

for d=1:4

    sheetname=['Day ', num2str(d)];

   [junk, datainfo]=xlsread(xlsfilename,sheetname, 'a1:d1');

   subnum=xlsread(xlsfilename, sheetname, 'a2:a19');

   data=xlsread(xlsfilename, sheetname, 'b2:d19');

end

who  

 

 

Your variables are:

 

d            data         datainfo     junk         sheetname    subnum       xlsfilename    

 

xlsread is generally pretty straightforward when reading in numeric values. When reading in text, or a combination of numeric values and text things are a little more complicated. The first argument returned from xlsread is any numeric data contained within the range of cells syou are reading from. The second argument is any text. So, in the line [junk, datainfo]=xlsread(xlsfilename,sheetname, 'a1:d1'); because we are reading a set of text, junk will be empty and it is the second argument, datainfo, that will contain the text information.

 

Reading in and out of a text file

 

This program MatlabTextFile.m writes and reads data into a standard text file.

 

% MatlabTextFile.m

%

% Writes and reads data from a text file.

 

clear all

 

txtfilename='MatlabTextFile.txt';

colStr={'Subject', 'Resp1', 'Resp2', 'Resp3'};

nSub=18;

 

% open file

fp=fopen(txtfilename, 'wt');  

 

We begin by opening the text file to be read, and returning a file pointer to that file. In this case we specify that we want to read to the file using ‘r’. Other options include writing to a file ‘w’ or appending data to a file ‘a’. doc fopen will give you a list of the possible options.

 

We then check to see that the file opened successfully. There are lots of reasons a file may not open, for example, if you already have that file open using a text editor, or the file isn’t in your Matlab path.

 

if fp==-1

    disp('sorry could not open file')

else

    for d=1:4

        fprintf(fp, '%s\n', ['Day ', num2str(d)]);

 

        for i=1:length(colStr)

            fprintf(fp,'%s\t', colStr{i});

        end

        fprintf(fp,'\n');

        for i=1:nSub

            fprintf(fp, '%d\t', i);

            fprintf(fp, '%.3f', rand(1, 3));

            fprintf(fp,'\n');

        end

    end

end

disp(['Text spreadsheet created in ', pwd]);

fclose(fp);  

 

Text spreadsheet created in C:\Program Files\MATLAB\R2008a  

 

 

fprintf takes in the following arguments:

The file pointer specifying the file you want to read from,.

The type of data you want to write into from the file (‘%s’ = string, ‘%d’ = integer. ‘%f’ means double, use doc fprintf for more options). When writing a double you can either write using '%f' or specify the precision and after the decimal place: '%.3f' will round data to 3 decimal places.

An optional argument describing how many pieces of data you want to write.

 

Remember to close the file at the end of the program. If your program crashes before the end you would be wise to call fclose(fp) before re-running the program.

 

'\t' adds a tab, '\n' adds a new line.

 

Now let's read the data back in again.

 

fp=fopen(txtfilename, 'r');

 

if fp==-1

    disp('sorry could not open file')

else

    for d=1:4

        dayStr{d}=fscanf(fp, '%s', 2);

                   % Note how we read two strings into a single cell

 

        for i=1:4

            colStr{i}=fscanf(fp,'%s', 1);

        end

 

        for i=1:nSub

            subNum(i)=fscanf(fp, '%d', 1);

            respVals(i, :)=fscanf(fp, '%f', 3);

            % Note how we read three floats in at a time

        end

    end

end

 

fclose(fp)  

 

ans =

     0  

 

Working with fscanf tends to be a little fiddly since if you read the wrong thing in early, you get out of sync with the file, and every variable read in after that point gets messed up. If you try to read a float as if it's a string you will end up with nonsense. One trick for debugging is to make sure you close your file and clear all the read in variables (e.g. dayStr, colStr, respVals). Then go through the program line by line, checking that the right variable is being read in.