| MATLAB® | ![]() |
| On this page… |
|---|
Passing Filenames as Arguments Passing Filenames to ASCII 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 =
63Since 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
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.
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 syntaxIf you assign the output to a variable, you must use the function syntax.
savedData = load('mydata.mat')ASCII files are specified as follows. Here, the file extension is required.
load mydata.dat -ascii % Command syntax
load('mydata.dat','-ascii') % Function syntaxThere are several ways that your function code can work on specific files without you having to hardcode their filenames into the program. You can
Pass the filename in as an argument
function myfun(datafile)
Prompt for the filename using the input function
filename = input('Enter name of file: ', 's');Browse for the file using the uigetfile function
[filename, pathname] =
uigetfile('*.mat', 'Select MAT-file');For more information: See the input and uigetfile function reference pages.
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.
![]() | Save and Load | Input/Output | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |