Function definitions must appear at end of file

464 views (last 30 days)
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)

Accepted Answer

David Fletcher
David Fletcher on 4 Apr 2018
Edited: David Fletcher on 4 Apr 2018
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
  8 Comments
Arjun Panyam
Arjun Panyam on 4 Apr 2018
It's on a script called Project2 with other programs under headers %%Question 1 and %%Question 2, for some reason when I run just the %%Question 3 section of the program in a seperate script, it does not come up with the same error.
Walter Roberson
Walter Roberson on 5 Apr 2018
You cannot use the structure
some script
function
some more script
The %% sections are not treated separately: the restrictions apply to the entire file, that if you have a mix of function and script then the function must go at the bottom.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!