Error: Function definition not supported in this context. Create functions in code file.
4 次查看(过去 30 天)
显示 更早的评论
function xc = bisect(f,a,b,tol)
if sign(f(a))*sign(f(b)) >= 0,
error('f(a)f(b)<0 not satisfied!') %ceases execution
end
fa=f(a);
fb=f(b);
k = 0;
while (b-a)/2>tol
c=(a+b)/2;
fc=f(c);
if fc == 0 %c is a solution, done
break
end
if sign(fc)*sign(fa)<0 %a and c make the new interval
b=c;fb=fc;
else %c and b make the new interval
a=c;fa=fc;
end
end
xc=(a+b)/2;
0 个评论
回答(1 个)
Walter Roberson
2020-5-7
you need to store that code in a file named bisect.m
It is not possible to define this kind of function at the MATLAB command line.
2 个评论
Walter Roberson
2020-5-10
The error you got "Function definition not supported in this context" is caused by one of two things:
1) In R2016a or earlier, you tried to define a function inside a script -- that is, you had at least one executable line that is not inside any function before the function definition. Defining functions inside scripts is permitted in R2016b and later, and if you had made a mistake in defining a function inside a script in R2016b or later you would have received different error messages; or
2) You tried to define a function at the MATLAB command line, or inside code that you eval() or evalc(). For example,
>> function xc = bisect(f,a,b,tol)
function xc = bisect(f,a,b,tol)
↑
Error: Function definition not supported in this context. Create functions in code file.
It is not permitted to define a function at the MATLAB command line. Instead you need to give the command
edit ./bisect
and paste the code you show into the editor session that comes up, and save the file as bisect.m . Or instead of the "edit" command, you can use the toolbar New -> Script menu entries.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!