Main Content

Unexpected Results When Loading Variables Within a Function

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 i, j, mode, char, size, and path.

These unexpected results occur because when you execute a function, MATLAB preprocesses all the code in the function before running it. However, calls to load are 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 height, width, and length. If you load these variables in a function such as findVolume, MATLAB interprets the reference to length as a call to the MATLAB length function, 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 to the 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 calling load. To initialize a variable, assign it to an empty matrix or an empty character vector. For example:

    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 exist function. A return value of 5 determines that the name is a built-in MATLAB function.

See Also

Related Topics