MATLAB: Function definitions must appear at end of file

calling functionserror

I'm getting this error for this code snippet and I don't know why:
%psum.m
function[sum, steps] = psum(tol)
sum = 1.0;
steps = 1;
while abs(sum-pi^2/6.0) >= tol
steps = steps +1;
sum = sum + 1 / steps ^2;
end
end
%project2.m
tols = [0.1 0.05 0.01 0.005 0.001];
for i = 1 : 5
tols = [0.1 0.05 0.01 0.005 0.001];
[errors(i), totalSteps(i)] = psum(tols(i));
end
loglog(errors, tols, totalSteps, tols)

Best Answer

As it says, if you are going to have a function in the same file as a script, the function must go at the bottom. Until about version 2016b, the function had to go in a totally separate file.
It needs to be like this:
%project2.m
tols = [0.1 0.05 0.01 0.005 0.001];
for i = 1 : 5
tols = [0.1 0.05 0.01 0.005 0.001];
[errors(i), totalSteps(i)] = psum(tols(i));
end
loglog(errors, tols, totalSteps, tols)
%psum.m
function[sum, steps] = psum(tol)
sum = 1.0;
steps = 1;
while abs(sum-pi^2/6.0) >= tol
steps = steps +1;
sum = sum + 1 / steps ^2;
end
end