Advanced Matlab Programming: Flow Control
Advanced Matlab Programming: Flow Control
Flow Control
Conditional Control if, else, switch
Conditional statements enable you to select at run time which block of code to execute. The
simplest conditional statement is an if statement. For example:
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
if statements can include alternate choices, using the optional keywords elseif or else. For example:
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end
Alternatively, when you want to test for equality against a set of known values, use a switch
statement. For example:
[dayNum, dayString] = weekday(date, 'long', 'en_US');
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
Programming and Graphics
Page 1
Page 2
B = A;
B(1,1) = 0;
A == B
ans =
0
The proper way to check for equality between two variables is to use the isequal function:
if isequal(A, B), ...
isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix, as the
expression to be evaluated by the if function. Using the A and B matrices from above, you get
isequal(A, B)
ans =
0
Here is another example to emphasize this point. If A and B are scalars, the following program will
never reach the "unexpected situation". But for most pairs of matrices, including our magic squares
with interchanged columns, none of the matrix conditions A > B, A < B, or A == B is true for all
elements and so the else clause is executed:
if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end
Page 3
isequal
isempty
all
any
Loop Control for, while, continue, break
This section covers those MATLAB functions that provide control over program loops.
for
The for loop repeats a group of statements a fixed, predetermined number of times. A matching end
delineates the statements:
for n = 3:32
r(n) = rank(magic(n));
end
r
The semicolon terminating the inner statement suppresses repeated printing, and the r after the
loop displays the final result.
It is a good idea to indent the loops for readability, especially when they are nested:
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end
Page 4
Page 5
Page 6
Is this result true whichever value of x we start with? (You can nd out about the command isprime
by typing help isprime.)
Task 5: Write a loop structure which iterates xn+1 =5xn|1 for xn = 1/7 until it returns to the same
value (use while).
Page 7
Page 8
Page 9
Page 10
The hold function determines whether new graphics objects are added to the graph or
replace objects in the graph.
hold on retains the current plot and certain axes properties so that subsequent graphing
commands add to the existing graph.
hold off resets axes properties to their defaults before drawing new plots. hold off is the
default.
hold all holds the plot and the current line color and line style so that subsequent plotting
commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the
list. Plotting commands continue cyclicing through the predefined colors and linestyles from where
the last plot stopped in the list.
3) plot3
The plot3 function displays a three-dimensional plot of a set of data points.
plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or matrices, plots one or more lines in
three-dimensional space through the points whose coordinates are the elements of X1, Y1,
and Z1.
plot3(X1,Y1,Z1,LineSpec,...) creates and displays all lines defined by the Xn,Yn,Zn,LineSpec
quads, where LineSpec is a line specification that determines line style, marker symbol, and
color of the plotted lines.
Example : Plot a three-dimensional helix.
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
grid on
axis square
Page 11
subplot
subplot divides the current figure into rectangular panes that are numbered row wise. Each pane
contains an axes. Subsequent plots are output to the current pane.
subplot(m,n,p) creates an axes in the pth pane of a figure divided into an m-by-n matrix of
rectangular panes. The new axes becomes the current axes.
Examples
To plot income in the top half of a figure and outgo in the bottom half,
income = [3.2 4.1 5.0 5.6];
outgo = [2.5 4.0 3.35 4.9];
subplot(2,1,1); plot(income)
subplot(2,1,2); plot(outgo)
4) loglog
loglog(Y) plots the columns of Y versus their index if Y contains real numbers. If Y contains
complex numbers, loglog(Y) and loglog(real(Y),imag(Y)) are equivalent. loglog ignores the
imaginary component in all other uses of this function.
loglog(X1,Y1,...) plots all Xn versus Yn pairs. If only Xn or Yn is a matrix, loglog plots the
vector argument versus the rows or columns of the matrix, depending on whether the
vector's row or column dimension matches the matrix.
loglog(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples, where
LineSpec determines line type, marker symbol, and color of the plotted lines. You can mix
Xn,Yn,LineSpec triples with Xn,Yn pairs
Page 12
5) semilogx, semilogy
semilogx and semilogy plot data as logarithmic scales for the x- and y-axis, respectively,
logarithmic.
semilogx(Y) creates a plot using a base 10 logarithmic scale for the x-axis and a linear scale
for the y-axis. It plots the columns of Y versus their index if Y contains real numbers.
semilogx(Y) is equivalent to semilogx(real(Y), imag(Y)) if Y contains complex numbers.
semilogx ignores the imaginary component in all other uses of this function.
semilogx(X1,Y1,...) plots all Xn versus Yn pairs. If only Xn or Yn is a matrix, semilogx plots the
vector argument versus the rows or columns of the matrix, depending on whether the
vector's row or column dimension matches the matrix.
semilogx(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples. LineSpec
determines line style, marker symbol, and color of the plotted lines.
Examples : Create a simple semilogy plot.
x = 0:.1:10;
semilogy(x,10.^x)
Page 13
set(get(AX(1),'Ylabel'),'String','Left Y-axis')
set(get(AX(2),'Ylabel'),'String','Right Y-axis')
xlabel('Zero to 20 \musec.')
title('Labeling plotyy')
set(H1,'LineStyle','--')
set(H2,'LineStyle',':')
Page 14
Page 15
Page 16
first as a x-y plot, then as a polar plot. Use subplot to keep them in the same figure.
Task 2: Plot
range being ,
What should you do about x=0? Hint: read help on eps.
Task 3: Try to duplicate the plot shown here. Hint-1: use the sin function itself to calculate the points
where the annotation should be located. Hint- 2: try using \leftarrow in your strings.
Page 17
Page 18
Page 19
8 3 7;
9 6 8;
5 5 5;
4 2 3];
Create stacked bar graphs using the optional 'stack' argument. For example,
bar(Y,'stack')
grid on
set(gca,'Layer','top') % display gridlines on top of graph
creates a 2-D stacked bar graph, where all elements in a row correspond to the same x location.
Page 20
Page 21
Page 22
3. To ensure that the second axes does not interfere with the first, locate the y-axis on the right
side of the axes, make the background transparent, and set the second axes' x tick marks to
the empty matrix:
set(h2,'YAxisLocation','right','Color','none','XTickLabel',[])
4. Align the x-axis of both axes and display the grid lines on top of the bars:
set(h2,'XLim',get(h1,'XLim'),'Layer','top')
Page 23
9 6 8;
5 5 5;
4 2 3];
harea = area(Y)
% This returns handles to three hggroups (areaseries objects)
grid on
Change the face color of each layer to make the plot more readable:
set(harea(1),'FaceColor',[.5 .8 .9])
set(harea(2),'FaceColor',[.7 .9 .1])
set(harea(3),'FaceColor',[.9 1 1])
Page 24
Pie Charts
Pie charts are a useful way to communicate the percentage that each element in a vector or matrix
contributes to the sum of all elements. pie and pie3 create 2-D and 3-D pie charts. A 3-D pie chart
does not show any more or different information than a 2-D pie chart does; it simply adds depth to
the presentation by plotting the chart on top of a cylindrical base.
This example shows how to use the pie function to visualize the contribution that three
products make to total sales. Given a matrix X where each column of X contains yearly sales figures
for a specific product over a five-year period:
X = [19.3 22.1 51.6;
Sum each row in X to calculate total sales for each product over the five-year period.
x = sum(X);
You can offset the slice of the pie that makes the greatest contribution using the explode input
argument. This argument is a vector of zero and nonzero values. Nonzero values offset the
respective slice from the chart.
First, create a vector containing zeros:.
explode = zeros(size(x));
Then find the slice that contributes the most and set the corresponding explode element to 1:
[c,offset] = max(x);
explode(offset) = 1;
Page 25
Page 26
Page 27
Description
Hist
Rose
You can specify the number of bins to use as a scalar second argument. If omitted, the default is 10
(hist) or 20 (rose). Data values passed to hist can be in any units and can be n-by-m, but rose expects
values to be in radians in a 1-by-n or n-by-1 vector. The height (or length when using rose) of the
bins represents the number of values that fall in each bin. You can also vary the size of bins by
specifying a vector for apportioning bin widths as the second argument.
Histograms in Cartesian Coordinates
The hist function shows the distribution of the elements in Y as a histogram with equally spaced bins
between the minimum and maximum values in Y. If Y is a vector and is the only argument, hist
creates up to 10 bins. For example:
yn = randn(10000,1);
hist(yn)
generates 10,000 random numbers and creates a histogram with 10 bins distributed along the x-axis
between the minimum and maximum values of yn.
Page 28
Page 29
Page 30
Description
Stem
stem3
Stairs
Page 31
Page 32
Page 33
% Time limits
s = 0.1+i;
% Spiral rate
y = exp(-s*t);
Using t as magnitudes that increase with time, create a spiral with increasing height and draw a
curve through the tops of the stems to improve definition:
stem3(real(y),imag(y),t)
hold on
plot3(real(y),imag(y),t,'r')
Page 34
Stairstep Plots
Stairstep plots display data as the leading edges of a constant interval (i.e., zero-order hold state).
This type of plot holds the data at a constant y value for all values between x(i) and x(i+1), where i is
the index into the x data. This type of plot is useful for drawing time-history plots of digitally sampled
data systems.
Example Stairstep Plot of a Function
Define a function f that varies over time:
alpha = 0.01;
beta = 0.5;
t = 0:10;
f = exp(-alpha*t).*sin(beta*t);
stairs(t,f)
hold on
plot(t,f,'--*')
hold off
Finally, annotate the graph and set the axes limits:
label = 'Stairstep plot of e^{-(\alpha*t)} sin\beta*t';
text(0.5,-0.2,label,'FontSize',14)
xlabel('t = 0:10','FontSize',14)
axis([0 10 -1.2 1.2])
Page 35
Page 36
Page 37
Page 38