5.4: Naming Functions
- Page ID
There are a few “gotchas” that come up when you start defining functions. The first is that the “real” name of your function is determined by the file name, not by the name you put in the function signature. As a matter of style, you should make sure that they are always the same, but if you make a mistake, or if you change the name of a function, it’s easy to get confused.
In the spirit of making errors on purpose, edit myfunc.m and change the name of the function from
something_else, like this:
function res = something_else (x) s = sin(x); c = cos(x); res = abs(s) + abs(c); end
Now call the function from the Command Window, like this:
>> y = myfunc(1) y = 1.3818
The function is still called
myfunc, because that’s the name of the file. If you try to call it like this:
>> y = something_else(1) Undefined function or variable 'something_else'.
It doesn’t work. The name of the file is what matters; the name of the function is ignored.
The second “gotcha” is that the name of the file can’t have spaces. For example, if you rename the file to my func.m and try to run it, you get:
>> y = my func(1) y = my func(1) | Error: Unexpected MATLAB expression.
This fails because MATLAB thinks
func are two different variable names.
The third “gotcha” is that your function names can collide with built-in MATLAB functions. For example, if you create an M-file named sum.m and then call
sum, MATLAB might call your new function, not the built-in version! Which one actually gets called depends on the order of the directories in the search path and (in some cases) on the arguments. As an example, put the following code in a file named sum.m:
function res = sum(x) res = 7; end
And then try this:
>> sum(1:3) ans = 6 >> sum ans = 7
In the first case MATLAB used the built-in function; in the second case it ran your function! This kind of interaction can be very confusing. Before you create a new function, check to see if there is already a MATLAB function with the same name. If there is, choose another name!