Function definitions must appear at end of file
33 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
David Fletcher
2018-4-4
编辑:David Fletcher
2018-4-4
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 个评论
Walter Roberson
2018-4-5
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!