Skip to Main Content Skip to Search
Product Documentation

Files and Filenames

Naming Functions

A valid name for a MATLAB function file is composed of a string of letters, digits, and underscores, totaling not more than namelengthmax characters and beginning with a letter.

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 a MATLAB function 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 the MATLAB function 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 is a folder (s.isdir).

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

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

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

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