MATLAB: How to save functions or sub functions in matlab

save-functions

Dear all, I know how to save variables, but how can I save functions or sub functions in matlab? Thanks..

Best Answer

It is not clear from your explanation where you are defining the function, but I can see two main possibilities which would generate that error (or a similar error):
  • Trying to define a function in the command window: this is not allowed in MATLAB, all functions must be saved in a file (except for anonymous functions).
  • Trying to define a function inside a script: only MATLAB versions from R2016B+ support functions defined in scripts. You need to read the documentation carefully for your version, not the online help (which is for the most recent version): for your MATLAB version it is not possible to define a function inside a script.
In practice if you want to define a function then do NOT have any code outside of any function declaration, e.g. this needs to be the entire file contents:
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end
You can add local functions to the same file, but NO CODE outside of those functions. Save the function as a file stat.m (you should use the same name as the function itself). Then it will work.