Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

LOOPS AND CONDITIONALS

Introduction:
Within any program, you can define sections of code that either repeat in a loop or conditionally execute.

In MATLAB, loops use the “for” or “while” keywords. Conditional statements use the keywords “if” or

“switch”. Pay close attention to terms in bold, as they will represent important keywords used in the

MATLAB syntax.

a. Loops:
All loops are written as self-contained blocks of code. These blocks start with the keyword and

terminate with the “end” statement.

The “for” loop allows you to repeatedly execute a command or a set of commands for a fixed
number of iterations. This loop uses a vector of values to determine for many times it will
execute.
A typical block of code using a for loop will have the following general appearance:

b. Conditional Statements:
A conditional statement allows you to execute a command or set of commands in case a given

Control systems LAB LAB


condition is true. The general form of the “if” statement is:

SUBMITTED TO: MAAM


KASHIF ANWAR MTS F-19 B ANAM MAQBOOL
The “else” and “elseif” sections are optional. “elseif” statements can be used as well as nested

“if” statements. The expression is usually of the form expression operation expression where
operations are ==, <, >, <=, >=, or ~ = where ~ denotes NOT operation.

Lab work:
TASK-1. Use your knowledge to define a vector make a matrix with the following properties.
a. The matrix should contain two rows
b. The first row contains even numbers from 1 to 10
c. The second row contains odd numbers from 11 to 20
Code and output:

Figure 1: Code/output task1


TASK-2
Generate the following vector using a “for” loop
A = [11 22 33 44 55 66]

Code and output:

Figure 2: Code/output task2

Description:
TASK-3
Make a matrix consisting of 5 elements. Using a “for” loop, find the product of all
the elements of the vector and store the result in a new variable

“p”.

Code and output:

Figure 3: Code/output task2

Description
TASK-3
What will be the output of the following code?

c = 2;

if c == 1

disp(“c is 1”)

elseif c==2

disp(“c is 2”)

else

disp(“c is neither 1 nor 2”).

end

Code and output:

Figure 4: Code and output task 4

Description:
CONCLUSION
This lab is a continuation of previous lab, which was a basic intro to syntax and plots in MATLAB. This
lab took us further into the use of MATLAB. While developing an algorithm, we will be using loops and
conditionals at every stage. So, the understanding of both these methods are important. This lab taught us
very well, how to use each according to our requirements.

You might also like