Function definitions must appear at end of file
477 views (last 30 days)
Show older comments
Arjun Panyam
on 4 Apr 2018
Commented: Walter Roberson
on 5 Apr 2018
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)
0 Comments
Accepted Answer
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
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.
More Answers (0)
See Also
Categories
Find more on Workspace Variables and MAT-Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!