Unexpected Results When Loading Variables Within a Function - MATLAB & Simulink (original) (raw)

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:

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

load