If you have a function that loads data from a MAT-file and find
that MATLAB® does not return the expected results, check whether
any variables in the MAT-file share the same name as a MATLAB function.
Common variable names that conflict with function names include
These unexpected results occur because when you execute a function, MATLAB preprocesses
all the code in the function before running it. However, calls to
not preprocessed, meaning MATLAB has no knowledge of the variables
in your MAT-file. Variables that share the same name as MATLAB functions
are, therefore, preprocessed as MATLAB functions, causing the
unexpected results. This is different from scripts, which MATLAB preprocesses
and executes line by line, similar to the Command Window.
For example, consider a MAT-file with variables
length. If you load these variables in a function
findVolume, MATLAB interprets the
length as a call to the MATLAB
and returns an error.
function vol = findVolume(myfile) load(myfile); vol = height * width * length; end
Error using length Not enough input arguments.
To avoid confusion, when defining your function, choose one (or more) of these approaches:
Load the variables into a structure array. For example:
function vol = findVolume(myfile) dims = load(myfile); vol = dims.height * dims.width * dims.length; end
Explicitly include the names of variables in the call
load function. For example:
function vol = findVolume(myfile) load(myfile,'height','width','length') vol = height * width * length; end
Initialize the variables within the function before
load. To initialize
a variable, assign it to an empty matrix or an empty character vector.
function vol = findVolume(myfile) height = ; width = ; length = ; load(myfile); vol = height * width * length;
To determine whether a particular variable name is associated
with a MATLAB function, use the
A return value of 5 determines that the name is a built-in MATLAB function.