Files and Filenames

Naming M-files

M-file names must start with an alphabetic character, may contain any alphanumeric characters or underscores, and must be no longer than the maximum allowed M-file name length (returned by the function namelengthmax).

N = namelengthmax
N =
    63

Since variables must obey similar rules, you can use the isvarname function to check whether a filename (minus its .m file extension) is valid for an M-file.

isvarname mfilename

Naming Other Files

The names of other files that MATLAB interacts with (e.g., MAT, MEX, and MDL-files) follow the same rules as M-files, but may be of any length.

Depending on your operating system, you may be able to include certain nonalphanumeric characters in your filenames. Check your operating system manual for information on valid filename restrictions.

Passing Filenames as Arguments

In MATLAB commands, you can specify a filename argument using the MATLAB command or function syntax. For example, either of the following are acceptable. (The .mat file extension is optional for save and load).

load mydata.mat           % Command syntax
load('mydata.mat')        % Function syntax

If you assign the output to a variable, you must use the function syntax.

savedData = load('mydata.mat')

Passing Filenames to ASCII Files

ASCII files are specified as follows. Here, the file extension is required.

load mydata.dat -ascii            % Command syntax
load('mydata.dat','-ascii')       % Function syntax

Determining Filenames at Run-Time

There are several ways that your function code can work on specific files without you having to hardcode their filenames into the program. You can

For more information: See the input and uigetfile function reference pages.

Returning the Size of a File

Two ways to have your program determine the size of a file are shown here.

  -- METHOD #1 --                    -- METHOD #2 --
s = dir('myfile.dat');         fid = fopen('myfile.dat');
filesize = s.bytes             fseek(fid, 0, 'eof');
                               filesize = ftell(fid)
                               fclose(fid);

The dir function also returns the filename (s.name), last modification date (s.date), and whether or not it's a directory (s.isdir).

(The second method requires read access to the file.)

For more information: See the fopen, fseek, ftell, and fclose function reference pages.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS