Why do I receive an error when attempting to run my script?

I receive the error
A function declaration cannot appear within a script MATLAB file.
when I attempt to run my script.

 Accepted Answer

This error message appears because the keyword "function", which starts a function declaration, cannot appear inside a script (a MATLAB file that does not start with a function declaration line). The attached SCRIPT_ERR file is an example of a MATLAB file that returns such an error.
This is due to the differences in the way scripts and functions are parsed and interpreted in MATLAB.
The two ways to correct this problem are to change your script file to a function file by adding a function declaration line to the first line of the script, or to move the function into a separate file and simply call it inside the script file. The attached CORR_FUNC MATLAB file exhibits the former workaround, that is, the script file was changed into a function file.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!