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)

采纳的回答

David Fletcher
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 个评论
Arjun Panyam
Arjun Panyam 2018-4-4
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 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 CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by