I'm on MATLAB R2014b and have a question that I will illustrate with the following example.
MWE can be made as follows or download it as a .zip file here.
Create a package folder +test
on your path with four function files in it:
+test
a.m
b.m
c.m
d.m
Content of a.m
:
function a
disp 'Hello World!'
Content of b.m
:
function b
a
If you run b
from the command line, you will have to import the test
package first (import test.*
) or run test.b
.
Running b
will result in an error, since the scope of function b
doesn't contain function a
. We must import it before it can be used. For this I've created c.m
:
function c
import test.*
a
Now running c
works fine.
Now my question. If I change c.m
to (saved in d.m
):
function d
a
import test.*
I.e. the import command is issued after the call to package function a
. Running d
still works just fine, as if the position of the import command in d.m
does not matter. The import appears to have occurred before the call to function a
, which in d.m
happens on the line before the import.
Why does this happen. Is this the intended behaviour and what are its uses? How and in what order does MATLAB read a .m
file and process it? And more off-topic, but in general: how is importing packages handled in different languages compared to MATLAB, does the order of commands matter?
My preemptive conclusion based on the comments: It is probably best practice to only use the import function at or near the beginning of MATLAB code. This makes clearly visible the imported content is available throughout the entire element (e.g. function). It also prevents the incorrect assumption that before the import, the content is not yet available or refers to a different thing with the same name.