Friday, 13 November 2015

Matlab definition of functions, and function definition errors

I was trying to create a new function in Matlab, and had some issues as I am relatively unfamiliar with the format.

When writing a function, it must go in a .m file, and only the function can go in the .m file, no other code.  The typical syntax for a function

function output_variable=function_name(input_variable)

output_variable = 2* input_variable

end
The above function then should go in a file named function_name.m. Furthermore, to use the function, the code does not need to be executed first. The "current folder" must contain the .m script, and then just use the function name with variables if needed. Comments are also allowed.

If the function contains any code outside of the function, the following error will be seen:

This statement is not inside any function.
 (It follows the END that terminates the definition
 of the function "create_const_mat".)

In this case, remove any code before the first line defining the function name, or after the end line.

If the function is saved in a .m file with a different name from the function, the following error will be seen:

Error: Function definitions are not permitted in this
context.

To solve this error, rename the .m file to match the function name, or conversely rename the function name to match the .m file name.

If executing the code in the function, then there are other possible errors, which will depend on the variables in the current workspace, and whether they match the variables needed by the function. If, your function requires varaibles which are not defined, then expect the following error:

Not enough input arguments.

If they are defined incorrectly, then anything could happen.

No comments:

Post a Comment