-Techniques and tricks‎ > ‎Matlab‎ > ‎

Files and directories (saving, loading, paths)

How annoying!  The solution depends on the particular situation.
A) Suppose you are running a program myprogram in a particular directory (say, 'C:\Blah\Documents\MATLAB'), generating a figure, and then you need to save the output in a particular other folder C:\Blah\MyData.  Try the following:  first, addpath(['C:\Blah\Documents\MATLAB']);  This will add the directory where myprogram lives to Matlab's search path, so it will look there even if you aren't in that directory.  Then, use cd('C:\Blah\MyData') to move to the data directory.  This is the location where Matlab should start you when you select Save from the File menu.
B) Suppose you have written a program like myprogram above, and you want to automatically save some output files to the directory without having to go through choosing Save from the File menu.  You can do this directly from the function.  Go to the line where you created a figure or a plot; this can either be a call to the command figure, or, if there is no figure open and one calls a drawing operation like plot, then a figure will automatically be opened. If there is a call to figure, make sure the figure number is also being returned as a variable, like myfig = figure; If it is being done indirectly by a drawing operation, then simply add in an explicit call to figure before the first drawing operation, like myfig = figure; .  At the end of the program, after the drawing is done, you can have it be automatically saved by using saveas(myfig,'myfigure.fig').  If you want to make sure it is being saved, you could also have it print out a report by using 2 lines: saveas(myfig,'myfigure.fig'); disp(['Just saved figure data to '  'myfigure.fig' ]);

 2. How do I read or write text or binary data from a file? 

When reading files that are in Matlab's native format, or when reading simple data formats like tab-delimited text, one can use built-in loading functions such as load or dlmread. When the file format requires a more complicated treatment, it is helpful to use the 'C-like' file and string functions fopen, fclosefread, fseek, frewind, fscanffgets, fgetlfwrite, fprintf.

Example 1:  Suppose we have a text file of parameters that we'd like to read into a structure.  The file might be in the format of VH Lab Labview analog input header file, and suppose it has the name vhlvanaloginput.vlh:
ChannelString: <tab> Dev1/ai0:15, Dev1/ai63
NumChans: <tab> 17
SamplingRate: <tab> 25000.000000
SamplesPerChunk: <tab> 25000
The format is field name, followed by a colon (:), followed by a tab, followed by the value.
We could read it with the following code:
function mystruct = readvhlvheaderfile(myfilename)
mystruct.emptyfield = 0; % make a new struct
mystruct = rmfield(mystruct,'emptyfield'); % make it have no fields
fid = fopen(myfilename);
if fid<0, error(['Could not open file ' myfilename '.']); end; % handle any errors nicely
mynextline = 0;
while mynextline~=-1, % this will be -1 if fgetl can't read anything else
mynextline = fgetl(fid);
myseparator = strfind(mynextline, sprintf(':\t') ); % prints the string ':' followed by the tab character
if ~isempty(myseparator),  % if we find an instance of the separator on this line, it is valid
try      %first, try to evaluate the expression so if it is numerical, it will become a number
eval(['mystruct = setfield(mystruct,mynextline(1:myseparator(1)-1),' mynextline(myseparator(1)+2:end) ');']);
catch, % but if this fails, set it to the string contents
mystruct = setfield(mystruct,mynextline(1:myseparator(1)-1),mynextline(myseparator(1)+2:end));
end;
end;
end
fclose(fid); % close our file

Example 2:  For an example of how to search for certain strings in a text file such as an XML file, see readprairieviewxml.m.

Example 3:  You want to read 10000 double samples of a binary file that has a header portion of length 500 bytes.  The binary data is coded in 'big endian' format.
fid = fopen(myfilename); % open the file
if fid<0, error(['Could not open file ' myfilename '.']); end;
fseek(fid,500,'bof');  % seek 500 bytes from the beginning of the file, that is, skip the first 500 bytes
mydata = fread(fid,10000,'double',0,'ieee-be'); % read 10000 samples of size double, no skipping, use big-endian format
fclose(fid); % close the file


Most of the time, when we write a Matlab file, we use the save command as in the following: 
save myfilename variable1 variable2 
This creates a new file called myfilename.mat and saves the contents of variable1 and variable2 into the file. Equivalently, one may use the following forms: 
save myfilename.mat variable1 variable2 
    or 
save myfilename.mat variable1 variable2 –mat 

The –mat option indicates that the file should be saved in Matlab format. 

However, one can also write a file myfilename that will not have the .mat extension if one uses the following syntax: 

save myfilename variable1 variable2 –mat 

This will create an identical file to the ones generated by the commands above, but the file will not have the .mat extension. This creates confusion and is not good form; unfortunately, this is how I (SDV) wrote my code for several years. 

To read a typical .mat file that includes the .mat extension, one can use the usual forms of the built-in Matlab function load: 

load myfilename or load('myfilename') or myvars = load('myfilename') or 
load myfilename.mat or load('myfilename.mat') or myvars = load('myfilename.mat') 

However, if one has saved a file in Matlab format without the .mat extension, one needs to use one of the following forms that pass the –mat argument explicitly in order to read the file:
 
load myfilename –mat or load('myfilename','-mat') or myvars = load('myfilename','-mat') 
Comments