0% found this document useful (0 votes)
70 views17 pages

Experiment #2

The document describes different types of flow control in MATLAB including if/elseif/else statements, switch/case statements, for loops, and while loops. It provides syntax examples and explanations of how each type of flow control works. Specific plotting commands in MATLAB like plot, bar, and stem are also summarized along with examples of their usage.

Uploaded by

Jhustine Cañete
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views17 pages

Experiment #2

The document describes different types of flow control in MATLAB including if/elseif/else statements, switch/case statements, for loops, and while loops. It provides syntax examples and explanations of how each type of flow control works. Specific plotting commands in MATLAB like plot, bar, and stem are also summarized along with examples of their usage.

Uploaded by

Jhustine Cañete
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

EXPERIMENT NO.

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

THE IF / ELSEIF / ELSE STATEMENT

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
==============================================================

SWITCH AND CASE STATEMENTS

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 among several cases based on expression.


The general form of the SWITCH statement is:

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.

The switch_expr can be a scalar or a string. A scalar switch_expr matches a case_expr if


switch_expr==case_expr. A string switch_expr matches a case_expr if strcmp(switch_expr,case_expr)
returns 1 (true).

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.

FOR Repeat statements a specific number of times.


The general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END

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.

The BREAK statement can be used to terminate the loop prematurely.

BREAK Terminate execution of WHILE or FOR loop.


BREAK terminates the execution of FOR and WHILE loops.
In nested loops, BREAK exits from the innermost loop only.

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 Repeat statements an indefinite number of times.


The general form of a WHILE statement is:

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 ~=.

The BREAK statement can be used to terminate the loop prematurely.

For example, (assuming A already defined):

A =1; B = 21

while abs(A-B) > 0


A = A+1;
B = B - 1;
end

4
Before we go to plotting, first generate this signal with the following parameters:

X=0:0.2:10;
Y=sin(X)

1. PLOT Linear plot.


Plot (X,Y) plots vector Y versus X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of
the matrix, whichever line up.
If X is a scalar and Y is a vector, length (Y) disconnected points are plotted.

PLOT (Y) plots the columns of Y versus their index.


If Y is complex , PLOT (Y) is equivalent to PLOT ( real (Y), imag( Y ) ).
In all other uses of PLOT, the imaginary part is ignored.

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:

b blue . point - solid


g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram

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 cycles over the axes LineStyleOrder property.

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.

2. BAR Bar Graph

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

BAR(...,'grouped') produces the default vertical grouped bar chart.


BAR(...,'stacked') produces a vertical stacked bar chart.
BAR(...,LINESPEC) uses the line color specified (one of 'rgbymckw').

H = BAR(...) returns a vector of patch handles.

Use SHADING FACETED to put edges on the bars. Use SHADING FLAT to turn them off.

Examples: subplot(3,1,1), bar(rand(10,5),'stacked'), colormap(cool)


subplot(3,1,2), bar(0:.25:1,rand(5),1)
subplot(3,1,3), bar(rand(2,3),.75,'grouped')

3. STEM Discrete sequence or "stem" plot.

STEM(Y) plots the data sequence Y as stems from the x axis terminated with circles for the data value.

STEM(X,Y) plots the data sequence Y at the values specified in X.

STEM(...,'filled') produces a stem plot with filled markers.

STEM(...,'LINESPEC') uses the linetype specified for the stems and markers. See PLOT for possibilities.

H = STEM(...) returns a vector of line handles.

4. STAIRS Stairstep plot.


STAIRS(Y) draws a stairstep graph of the elements of vector Y.
STAIRS(X,Y) draws a stairstep graph of the elements in vector Y at the locations specified in X. The X-values
must be in ascending order and evenly spaced.
STAIRS(...,STYLE) uses the plot linestyle specified by the string STYLE.

H = STAIRS(X,Y) returns a vector of line handles.


[XX,YY] = STAIRS(X,Y) does not draw a graph, but returns vectors X and Y such that PLOT(XX,YY) is the
stairstep graph.

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.

6. FIGURE Create figure window.


FIGURE, by itself, creates a new figure window, and returns its handle.

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.

GCF returns the handle to the current figure.

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.

7. HOLD Hold current graph.


HOLD ON holds the current plot and all axis properties so that subsequent graphing commands add to the
existing graph.
HOLD OFF returns to the default mode whereby PLOT commands erase the previous plots and reset all axis
properties before drawing new plots.

HOLD, by itself, toggles the hold state.


HOLD does not affect axis autoranging properties.

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".

8. SUBPLOT Create axes in tiled positions.


H = SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of small axes, selects
the p-th axes for for the current plot, and returns the axis handle. The axes are counted along the top row of the
Figure window, then the second row, etc.

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.

SUBPLOT(m,n,p), if the axis already exists, makes it current.


SUBPLOT(m,n,p,'replace'), if the axis already exists, deletes it and creates a new axis.

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

1. GRID Grid lines.


GRID ON adds major grid lines to the current axes.
GRID OFF removes major and minor grid lines from the current axes.
GRID MINOR toggles the minor grid lines of the current axes.
GRID, by itself, toggles the major grid lines of the current axes.
GRID(AX,...) uses axes AX instead of the current axes.

GRID sets the XGrid, YGrid, and ZGrid properties of the current axes.

set(AX,'XMinorGrid','on') turns on the minor grid.

2. TITLE Graph title.


TITLE('text') adds text at the top of the current axis.

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.

3. XLABEL X-axis label.


XLABEL('text') adds text beside the X-axis on the current axis.

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.

4. YLABEL Y-axis label.


YLABEL('text') adds text beside the Y-axis on the current axis.

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:

1. Define the variables given below

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);

Fill up the table by changing the value of A and B

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

3. Clear all variables

4. Define the variables given below

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

6. Change the value of A and B and complete the table

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

7. Clear all variables

8. Define the following variables:


N = that has a value ranging from 0 to 50 with and increment of 1.
F = 100 Hz

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

1. Define the variables given below


T = 0:0.02:20; %[1]
A = sin(T); %[2]

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”

4. Get the amplitude and the frequency of the graph.

Amplitude : 1m (assuming unit is in meters)

Frequency : 0.16Hz (@T=6.2s)

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.

Amplitude : 5m (assuming unit is in meters)

Sine wave frequency : 0.161Hz

12
Sampling frequency : 0.238Hz

7. Draw the graph and give some analysis

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.

Amplitude : 2m (assuming unit is in meters)

Sine wave frequency : 0.161Hz

Sampling frequency : 0.5848Hz

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.

Amplitude : 2m (assuming unit is in meters)

Sine wave frequency : 0.16Hz

Sampling frequency : 0.594Hz

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.

wts = exp(-j * 2 * pi * (d/c)* f * sin(thetam) * [0:N-1] )

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

You might also like