Professional Documents
Culture Documents
Loops and Conditionals in MATLAB
Loops and Conditionals in MATLAB
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
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
“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:
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”.
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
end
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.