Experiment #2
Experiment #2
2
FLOW CONTROL
OBJECTIVE:
To be able to write programs that has loops.
To be familiar with MATLAB’S different plotting commands and be able to interpret the plots.
PROCEDURES
Matlab has several flow controls
If statement
Switch statements
For loops
While loops
IF
The if is a logical statement that evaluates a certain condition and executes a group of statements
when a given expression is true. The optional elseif and else provide execution of alternate groups
of statements. The end keyword is used to terminate the loops.
IF IF statement condition.
The general form of the IF statement is
IF expression
statements
ELSEIF expression
statements
ELSE
statements
END
The statements are executed if the real part of the expression has all non-zero elements. The
ELSE and ELSEIF parts are optional. Zero or more ELSEIF parts can be used as ell as nested IF's.
The operators that can be used to form expressions are as follows:
Operator Function
== equal to
< less than
> greater than
<= less than or equal to
>= greater than
1
===========================================================
Example
if I == J % if I is equal to J
A(I,J) = 2; % the value of A is equal to 2
elseif abs(I-J) == 1 % elseif the absolute value of I minus J is equal 1
A(I,J) = -1; % the value of A is equal to -1
else
A(I,J) = 0; %otherwise A will be zero
End % end of loop
==============================================================
The switch statement executes groups of statements based on a value of a variable or expression. The
keywords case and otherwise delineate the groups. Only the first matching case is executed. There must
always be an end to match the switch. The syntax that can be used for such loops are given below:
SWITCH switch_expr
CASE case_expr,
statement, ..., statement
CASE {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...OTHERWISE,
statement, ..., statement
END
The statements following the first CASE where the switch_expr matches the case_expr are executed.
When the case expression is a cell array (as in the second case above), the case_expr matches if any of
the elements of the cell array match the switch expression. If none of the case expressions match the
switch expression, then the OTHERWISE case is executed (if it exists). Only one CASE is executed and
execution resumes with the statement after the END.
Only the statements between the matching CASE and the next CASE, OTHERWISE, or END are executed.
Unlike C, the SWITCH statement does not fall through (so BREAKs are unnecessary).
2
Example (assuming METHOD exists as a string variable):
switch lower(METHOD)
case {'linear','bilinear'}
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
case 'nearest'
disp('Method is nearest')
otherwise
disp('Unknown method.')
end
FOR LOOPS
The for command repeats a groups of statements on a predetermined number of times. A matching end
delineates the statements.
It is better to indent loops for readability especially when used as nested loops.
The columns of the expression are stored one at a time in the variable and then the following statements,
up to the END, are executed. The expression is often of the form X:Y, in which case its columns are simply
scalars. Some examples (assume N has already been assigned a value).
Sample program
FOR I = 1:N,
FOR J = 1:N,
A(I,J) = 1/(I+J-1);
END
END
3
FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1
FOR E = EYE(N), ... END sets E to the unit N-vectors.
Long loops are more memory efficient when the colon expression appears in the FOR statement since the
index vector is never created.
WHILE STATEMENTS
The while loops repeat a group of statements indefinitely depending on a control of a logical condition. A
matching end delineates the statement.
WHILE expression
statements
END
The statements are executed while the real part of the expression has all non-zero elements. The
expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.
A =1; B = 21
4
Before we go to plotting, first generate this signal with the following parameters:
X=0:0.2:10;
Y=sin(X)
Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:
For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus at each data point; PLOT(X,Y,'bd') plots blue
diamond at each data point but does not draw any line.
PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by the (X,Y,S) triples, where the X's and Y's
are vectors or matrices and the S's are strings.
For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a solid yellow line interpolating green circles at the
data points.
The PLOT command, if no color is specified, makes automatic use of the colors specified by the axes
ColorOrder property. The default ColorOrder is listed in the table above for color systems where the
default is blue for one line, and for multiple lines, to cycle through the first six colors in the table. For monochrome
systems,
PLOT returns a column vector of handles to LINE objects, one handle per line.
5
The X,Y pairs, or X,Y,S triples, can be followed by parameter/value pairs to specify additional properties
of the lines.
BAR(X,Y) draws the columns of the M-by-N matrix Y as M groups of N vertical bars. The vector X must be
monotonically increasing or decreasing.
BAR(Y) uses the default value of X=1:M. For vector inputs, BAR(X,Y)
or BAR(Y) draws LENGTH(Y) bars. The colors are set by the colormap.
BAR(X,Y,WIDTH) or BAR(Y,WIDTH) specifies the width of the bars. Values of WIDTH > 1, produce overlapped
bars. The default value is WIDTH=0.8
Use SHADING FACETED to put edges on the bars. Use SHADING FLAT to turn them off.
STEM(Y) plots the data sequence Y as stems from the x axis terminated with circles for the data value.
STEM(...,'LINESPEC') uses the linetype specified for the stems and markers. See PLOT for possibilities.
Stairstep plots are useful for drawing time history plots of zero-order-hold digital sampled-data systems.
6
5. POLAR Polar coordinate plot.
POLAR(THETA, RHO) makes a plot using polar coordinates of the angle THETA, in radians, versus the radius
RHO.
POLAR(THETA,RHO,S) uses the linestyle specified in string S.
See PLOT for a description of legal linestyles.
You can use FIGURE comand to create another window for ploting; or HOLD ON command to merge all plots in one
figure window.
FIGURE(H) makes H the current figure, forces it to become visible, and raises it above all other figures on the
screen. If Figure H does not exist, and H is an integer, a new figure is created with handle H.
Execute GET(H) to see a list of figure properties and their current values. Execute SET(H) to see a list of figure
properties and their possible values.
Algorithm note:
HOLD ON sets the NextPlot property of the current figure and axes to "add".
HOLD OFF sets the NextPlot property of the current axes to "replace".
For example,
SUBPLOT(2,1,1), PLOT(income)
SUBPLOT(2,1,2), PLOT(outgo)
plots income on the top half of the window and outgo on the bottom half.
7
SUBPLOT(m,n,P), where P is a vector, specifies an axes position that covers all the subplot positions listed in P.
SUBPLOT(H), where H is an axis handle, is another way of making an axis current for subsequent plotting
commands.
SUBPLOT('position',[left bottom width height]) creates an axis at the specified position in normalized coordinates
(in the range from 0.0 to 1.0).
If a SUBPLOT specification causes a new axis to overlap an existing axis, the existing axis is deleted - unless the
position of the new and existing axis are identical.
For example, the statement SUBPLOT(1,2,1) deletes all existing axes overlapping the left side of the Figure
window and creates a new axis on that side - unless there is an axes there with a position that exactly
matches the position of the new axes (and 'replace' was not specified), in which case all other overlapping axes
will be deleted and the matching axes will become the current axes.
SUBPLOT(111) is an exception to the rules above, and is not identical in behavior to SUBPLOT(1,1,1).
For reasons of backwards compatibility, it is a special case of subplot which does not immediately create an axes,
but instead sets up the figure so that the next graphics command executes CLF RESET in the figure (deleting all
children of the figure), and creates a new axes in the default position. This syntax does not return a handle, so it
is an error to specify a return argument.
The delayed CLF RESET is accomplished by setting the figure's NextPlot to 'replace'.
FORMATTING PLOTS
GRID sets the XGrid, YGrid, and ZGrid properties of the current axes.
TITLE('text','Property1',PropertyValue1,'Property2',PropertyValue2,...)
sets the values of the specified properties of the title.
H = TITLE(...) returns the handle to the text object used as the title.
8
XLABEL('text','Property1',PropertyValue1,'Property2',PropertyValue2,...)
sets the values of the specified properties of the xlabel.
H = XLABEL(...) returns the handle to the text object used as the label.
YLABEL('text','Property1',PropertyValue1,'Property2',PropertyValue2,...)
sets the values of the specified properties of the ylabel.
H = YLABEL(...) returns the handle to the text object used as the label.
OBJECTIVE A
Procedure:
A=1 B = 10
2. Write a program using the if command that will give the following result:
a. value x = 200 if the difference of A and B is zero
b. value x = 500 if the difference is a negative number
c. value x = 100 if the difference is positive
Write the program syntax that you used on the space provided below:
if (A-B)==0
x=200;
else if (A-B)<0
x=500;
else, (A-B)>0
x=100;
end
end
disp('x='),disp(x);
A 1 2 3 4 5 6 7 8 9 10
B 10 9 8 7 6 5 4 3 2 1
X 500 500 500 500 500 100 100 100 100 100
9
A=1 B = 10 C = A-B
5. Write the simple program using the if command statement that will give the following result display
the string “The Difference of A and B is (answer)”
(answer): NEGATIVE if the answer in C is negative
POSITIVE if the answer in C is positive
ZERO if the answer in C is zero
A 1 2 3 4 5 6 7 8 9 10
B 10 9 8 7 6 5 4 3 2 1
C -9 -7 -5 -3 -1 1 3 5 7 9
Write the program syntax that you used on the space provided below:
if (A-B)==0
disp('The Difference of A and B is ZERO')
else if (A-B)>0
disp('The Difference of A and B is POSITIVE')
else, (A-B)<0
disp('The Difference of A and B is NEGATIVE')
end
end
9. Using the for command, write a program that will compute the value of the equation given below
with all the values of N. Write your program on the space provided below.
A = e( 2 F N sin 30)
for N = 0:1:50
for F=100
A=(exp(1))^(2*pi*F*N*(sin(30)));
disp(A)
end
end
10. Write a program that will increment the value of A by 1 as long as the value of A is not equal to
150. Use the while command to perform this flow control and write your program on the space
provided below. Use initial value of A= -10.
A=-10
while A<150
A=A+1
10
disp(A)
end
QUESTIONS:
Answer the following questions based on your understanding about the flow control. Write your answers on
the space provided.
1. What is the easiest flow control that you think is available in your matlab software? Justify your
answer.
In my opinion I think that the easiest flow control is the IF/ELSEIF/ELSE statement.
Because it is straightforward and can use a lot of different kinds of operators (==, <=, =>, <, >).
This makes the flow control simple yet profound and versatile.
2. What is the significance of using the flow control in writing programs containing numerical
analysis?
It makes it easier to create the ideal values that we want to achieve involving numerical
analysis and increase the efficiency by how accurate the approximation of the result.
3. What will happen to your program if there is no “end” command in the flow control? Answer this by
trying to run a program in MATLAB without putting an “end” in your program.
The program itself will not run and an icon with an exclamation point will pop out and will
highlight that the program is lacking an END that matches the designated type of flow control used.
OBJECTIVE B
PROCEDURE
2. Plot the sine wave derived from equation 2 vs the time from equation 1.
3. Put the time duration at the x-axis and label it “TIME”. Put the sine wave at y-axis and label it “AMPLITUDE”.
Label the plot as “SINE WAVE PLOT”
5. Now change the amplitude of the graph by modifying [2]. Change it to 2V.
11
Draw your figure and give some analysis.
Analysis:
The value of the period (T) remains the same even if the amplitude was changed, and this is due to the fact
that amplitude is completely independent of the speed of propagation and depends only on the amount of energy in
the wave. Hence, increasing the value of amplitude does not increase the frequency in this case.
6. Define the variables given below and plot the graph using the stem command.
T = 0:0.2:20; %[3]
A = 5*sin(T); %[4]
Get the amplitude, sine wave frequency and the sampling frequency of the graph.
12
Sampling frequency : 0.238Hz
Analysis:
The usage of STEM provides a more detailed graph compared to the PLOT command. With the values
obtained using STEM, we were able to solve for the sampling frequency which requires the amount of samples per
second.
8. Define the variables given below and plot the graph using the bar command.
T = 0:0.3:15; %[5]
A = 2*sin(T); %[6]
Get the amplitude, sine wave frequency and the sampling frequency of the graph.
13
9. Draw the graph and give some analysis
Analysis:
The BAR command executes a bar graph in the shape of the frequency, it is pretty similar to the STEM
command. The difference in value is due to the fact that both examples have different amplitudes and periods, hence
a different sampling frequency.
10. Define the variables given below and plot the graph using the stairs command.
T = 0:0.25:25; %[7]
A = 2*sin(T); %[8]
Get the amplitude, sine wave frequency and the sampling frequency of the graph.
14
11. Draw the graph and give some analysis
Analysis:
The STAIRS command compared to the PLOT is more detailed just like how BAR and STEM commands
were. The difference in the value again is due to the fact that the value of time is different compared to the previous
ones. i.e., the steps and increments used.
12. Define all the variable given below. We are about to see the radiation pattern of a 4-element antenna array
in polar form.
N=4;
c=3 x 108 m/s;
f=1 GHz;
lambda=c/f;
d=lambda/2;
thetam = 30*180/pi;
theta = linspace(-pi/2,pi/2,1024);
13. Solve the value of A for all values of theta using the program given below.
15
for bb = 1:length(theta)
p1 = exp( j * 2 * pi * (d/c) * f * sin(theta(bb))*[0:N-1] );
z1(bb) = p1*wts.';
end
14. Plot using the polar command. Draw your graph on the space provided below and give some analysis about
the graph.
figure(1)
plot(theta*180/pi, abs(z1),'r')
figure(2)
polar(theta,abs(z1),'r')
16
Analysis:
We can see that performing the given commands, we were able to map the polar coordinates of the peak
value obtained near the angle 330°, the line is tangent to the circle and has a value of 4. The direction of the
maximum radiation is independent of the number of elements in the array.
CONCLUSION:
In retrospect, this experiment showed me how proper way of using flow controls can
significantly increase the efficiency by which a designated program can achieve results. I also learned that
there isn’t only one way or one pattern in programming a particular given commands. The latter part of the
experiment showed how the different commands in graphing, (PLOT, BAR, STAIRS, STEM, etc.) provide
similar results but one has advantage over the other depending on the usage and situation. The
combination of both the flow control and graphing functions of MATLAB can be a gateway for researchers
and scientists that requires data to be tabulated and graphed orderly, to produce results in a hastier
manner.
17