Use Code Sections with Control Statements and Functions
Unexpected results can appear when using code sections within control statements and
functions because MATLAB automatically inserts section breaks that do not appear in the
Editor unless you insert section breaks explicitly. This is especially true when nested code
is involved. Nested code occurs wherever you place a control statement or function within
the scope of another control statement or function.
MATLAB automatically defines section boundaries in a code block, according to this
criteria:
- MATLAB inserts a section break at the top and bottom of a file, creating a code section
that encompasses the entire file. However, the Editor does not highlight the resulting
section, which encloses the entire file, unless you add one or more explicit code
sections to the file. - If you define a section break within a control flow statement (such as an if or while
statement), MATLAB automatically inserts section breaks at the lines containing the
start and end of the statement. - If you define a section break within a function, MATLAB inserts section breaks at the
function declaration and at the function end statement. If you do not end the function
with an end statement, MATLAB behaves as if the end of the function occurs
immediately before the start of the next function.
If an automatic break occurs on the same line as a break you insert, they collapse into one
section break.
Nested Code Section Breaks
The following code illustrates the concept of nested code sections:
t = 0:.1:pi*4;
y = sin(t);
for k = 3:2:9
%%
y = y + sin(k*t)/k;
if ~mod(k,3)
%%
display(sprintf('When k = %.1f',k));
plot(t,y)
end
end
Code Sections