Clear Filters
Clear Filters

Error: Function definition not supported in this context. Create functions in code file.

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

Answers (1)

Walter Roberson
Walter Roberson on 7 May 2020
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 Comments
Walter Roberson
Walter Roberson on 10 May 2020
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.

Sign in to comment.

Categories

Find more on Software Development Tools 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!