MATLAB: Error: Function definitions are not permitted in this context.

errorfunctions

HI,
I already went through the forums and I don't seem to understand the issue. I just switched to a new PC and this script/function was working on my old PC not more than a few hours ago. It's for displaying datestr with the data cursor. I got it from… https://www.mathworks.com/matlabcentral/newsreader/view_thread/265493 at the very bottom and it had worked perfectly. Now I get an error saying it's not permitted.
the saved file….
function txt = myupdatefcn(empt,event_obj)
% Customizes text of data tips
pos = get(event_obj,'Position');
txt = {['time: ',datestr(pos(1))],...
['amplitude: ',num2str(pos(2))]};

Best Answer

Up until R2016a, it was not permitted to have a file that started as a script but then had a function definition. A script is any .m file whose first non-comment is not 'function' or 'classdef'. For example, storing the following in a single .m file was not permitted up to R2016a:
disp( sq(3) )
function y = sq(x)
y = x.^2;
end
In R2016b that changed and the above is now permitted in a single .m file, provided that the functions defined have a different name than the name of the .m file.
One possibility is then that you had a setup like this and it was working on your old system because your old system used R2016b, but that your new computer uses R2016a or before, when this was an error.
For earlier versions, you should split up your .m so that any script is in a different file than your function definitions.
Related Question