SlideShare a Scribd company logo
electricalenggtutorial.blogspot.com
1
INTRODUCTION
In this lecture we will discuss about
another flow control method – Loop
control.
A loop control is used to execute a set
of commands repeatedly
The set of commands is called the body of
the loop
MATLAB has two loop control techniques
1. Counted loops - executes commands a
specified number of times
2. Conditional loops - executes commands
as long as a specified expression is
true
2
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
INTRODUCTION ….
• Counted loops are called ‘for’ loop
• Conditional loops are called ‘while’
loop
• Both Scripts and functions also
allow to loop using for and while
loops.
• The keyword “end” is used to show
the end of a Loop
• In while loops the Code for each
condition is separated by the
keyword “end”
3
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
FOR LOOP SYNTAX
for varname = min:max
statements
end
4
N=10;
for I = 1:N
A(I) = 1/(I+J-1);
end
for
j=1:10
Statements
done
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
5
WHILE LOOP SYNTAX
while
I<N
computations
done
change I
Initialize I, N
I=1;
N=10;
while I<=N
A(I)=1/(I+1);
I=I+1;
end
while condition is true
statements
end
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
6
FOR VS WHILE
FOR
Repeats for specified
number of times
ALWAYS executes
computation loop at
least once!!!
Can use + or –
increments
Can escape (BREAK)
out of
computational loop
WHILE
Will do computational
loop ONLY if while
condition is met
Be careful to
initialize while
variable
Can loop forever if
while variable is
not updated within
loop!!!
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
THE FOR LOOP
Other
Forms
7
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
THE FOR LOOP …
• Matlab creates vector from 1
with an increment of 1,([ 1 2
… 10]), and execute the
commands for each value of ii.
• Matlab creates a vector with
an increment of 2, as [ 1 3 5
…9],and execute the commands
for each value of ii.
• Here the values of ii are
defined by user as [5 9 7].
The commands are executed for
these specific values.
• Here the increment is negative
8
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
FOR LOOP EXAMPLES
1. A program to print the numbers from 1 to
10
for i=1:10
disp(i)
end
2. A program to calculate the sum of squares
of numbers from 1 to n.
n=input('plz enter the no: ');
s=0;
for i=1:n
s=s+i^2;
end
disp(s)
9
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
FOR LOOP EXAMPLES
3. Calculate the factorial of any number n
n=input ('enter any integer ');
f=1;
for i=1: n
f=f*i;
end
disp(f)
4. Find the number of positive numbers in a vector
x = input( 'Enter a vector: ' );
count = 0;
for ii = 1:length(x),
if ( x(ii) > 0 ),
count = count + 1;
end
end
fprintf('Number of positive numbers is %dn',
count);
10
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
FOR LOOP ELECTRICAL ENGINEERING APPLICATION
Where Vci is the initial capacitor voltage; Vcf is
the voltage the capacitor will reach if it charges
for an infinite amount of time.
11
Plot the switching response of a given RC
circuit
 





 
msforteVVV
mstforV
tV RCtt
cfcicf
ci
c
5.1)(
5.10
/)( 0
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
FOR LOOP ELECTRICAL ENGINEERING APPLICATION …
Vci = input('Enter initial capacitor
voltage, Vci: ');
Vcf = input('Enter Final capacitor
voltage, Vcf: ');
R = input('Enter Resistance value, R:
');
C = input('Enter Capacitance value,
C: ');
t0 = input('Enter Switching time, t0:
');
tf = input('Enter Simulation end
time, tf: ');
t=linspace(0,tf,1000);
Vc=zeros(1,1000);
for i=1:1000
if t(i)<t0
Vc(i)=Vci;
else Vc(i)=Vcf+(Vci-Vcf)*exp(-(t(i)-
t0)/(R*C));
end
end
plot(t*1000,Vc);
title('RC Step Response')
ylabel('Capacitor voltage')
xlabel('time in msec')
grid on
12
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
THE WHILE LOOP
• The while- loop used when the number of loop
iterations is unknown
• Number of iteration is controlled by a condition.
• We can test the condition in each iteration and
stop looping when it is false.
• For example,
• Keep reading data from a file until you reach the end
of the file
• Keep adding terms to a sum until the difference of the
last two terms is less than a certain amount.
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
13
1. Loop evaluate conditional expression
2. If conditional-expression is true,
executes code in body, then goes back
to Step 1
3. If conditional-expression is false,
skips the body and goes to code after
end-statement
Note:
Body of loop must change value of
variable
There must be some value of the variable
that makes the conditional expression be
false
14
THE WHILE LOOP …
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
INFINITE LOOP
If the conditional expression never
becomes false, the loop will keep
executing... forever!
This condition is called as an
infinite loop.
This can happen in different ways
• No proper condition statement
• The condition variable is not
updated in the body of loop
If your program gets caught in an
infinite loop, Press CTRL+C
15
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
WHILE LOOP EXAMPLES
1. A program to print the numbers from 1
to 10
i = 1;
while i<=10
disp(i)
i = i +1
end
2. A program to display powers of 2.
x = 1
while x <= 15
x = 2*x
end
16
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
WHILE LOOP EXAMPLES …
3. Program ask the user to input a number
between 1 and 10
value = input ('Please Enter a Number betwee
n 1 and 10 (1-10)');
while ( value < 1 || value > 10)
fprintf('Incorrect input, please try again
.n');
value = input ('Enter a Number between 1 a
nd 10 (1-10)');
end
17
e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
Ad

Recommended

Loops in matlab
Loops in matlab
TUOS-Sam
 
Matrices, Arrays and Vectors in MATLAB
Matrices, Arrays and Vectors in MATLAB
Abu Raihan Ibna Ali
 
1. Linear Algebra for Machine Learning: Linear Systems
1. Linear Algebra for Machine Learning: Linear Systems
Ceni Babaoglu, PhD
 
SHA 1 Algorithm.ppt
SHA 1 Algorithm.ppt
Rajapriya82
 
Algorithm and Data Structures - Basic of IT Problem Solving
Algorithm and Data Structures - Basic of IT Problem Solving
coolpie
 
String matching algorithm
String matching algorithm
Alokeparna Choudhury
 
Knapsack problem using greedy approach
Knapsack problem using greedy approach
padmeshagrekar
 
10.Design Of Two Pass Assembler in system software.pdf
10.Design Of Two Pass Assembler in system software.pdf
SwapnaliPawar27
 
Conditional Control in MATLAB Scripts
Conditional Control in MATLAB Scripts
Shameer Ahmed Koya
 
Database connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
An overview of Hidden Markov Models (HMM)
An overview of Hidden Markov Models (HMM)
ananth
 
Sets and disjoint sets union123
Sets and disjoint sets union123
Ankita Goyal
 
Basic matlab and matrix
Basic matlab and matrix
Saidur Rahman
 
1.10. pumping lemma for regular sets
1.10. pumping lemma for regular sets
Sampath Kumar S
 
Python Pandas
Python Pandas
Sunil OS
 
The Maximum Subarray Problem
The Maximum Subarray Problem
Kamran Ashraf
 
Complexity analysis in Algorithms
Complexity analysis in Algorithms
Daffodil International University
 
Stressen's matrix multiplication
Stressen's matrix multiplication
Kumar
 
2.4 derivations and languages
2.4 derivations and languages
Sampath Kumar S
 
Graph coloring using backtracking
Graph coloring using backtracking
shashidharPapishetty
 
Knapsack Problem
Knapsack Problem
Jenny Galino
 
Matrix chain multiplication
Matrix chain multiplication
Respa Peter
 
Python reading and writing files
Python reading and writing files
Mukesh Tekwani
 
Micro operations
Micro operations
Ramakrishna Reddy Bijjam
 
NUMPY
NUMPY
Global Academy of Technology
 
File handling in Python
File handling in Python
Megha V
 
Matlab Functions
Matlab Functions
Umer Azeem
 
Back patching
Back patching
santhiya thavanthi
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
Shameer Ahmed Koya
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLAB
Shameer Ahmed Koya
 

More Related Content

What's hot (20)

Conditional Control in MATLAB Scripts
Conditional Control in MATLAB Scripts
Shameer Ahmed Koya
 
Database connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
An overview of Hidden Markov Models (HMM)
An overview of Hidden Markov Models (HMM)
ananth
 
Sets and disjoint sets union123
Sets and disjoint sets union123
Ankita Goyal
 
Basic matlab and matrix
Basic matlab and matrix
Saidur Rahman
 
1.10. pumping lemma for regular sets
1.10. pumping lemma for regular sets
Sampath Kumar S
 
Python Pandas
Python Pandas
Sunil OS
 
The Maximum Subarray Problem
The Maximum Subarray Problem
Kamran Ashraf
 
Complexity analysis in Algorithms
Complexity analysis in Algorithms
Daffodil International University
 
Stressen's matrix multiplication
Stressen's matrix multiplication
Kumar
 
2.4 derivations and languages
2.4 derivations and languages
Sampath Kumar S
 
Graph coloring using backtracking
Graph coloring using backtracking
shashidharPapishetty
 
Knapsack Problem
Knapsack Problem
Jenny Galino
 
Matrix chain multiplication
Matrix chain multiplication
Respa Peter
 
Python reading and writing files
Python reading and writing files
Mukesh Tekwani
 
Micro operations
Micro operations
Ramakrishna Reddy Bijjam
 
NUMPY
NUMPY
Global Academy of Technology
 
File handling in Python
File handling in Python
Megha V
 
Matlab Functions
Matlab Functions
Umer Azeem
 
Back patching
Back patching
santhiya thavanthi
 

Viewers also liked (20)

MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
Shameer Ahmed Koya
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLAB
Shameer Ahmed Koya
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2
Shameer Ahmed Koya
 
MATLAB Scripts - Examples
MATLAB Scripts - Examples
Shameer Ahmed Koya
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
Shameer Ahmed Koya
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
Shameer Ahmed Koya
 
Matlab loops
Matlab loops
pramodkumar1804
 
Abstract Class Presentation
Abstract Class Presentation
tigerwarn
 
Mat lab workshop
Mat lab workshop
Vinay Kumar
 
Matlab lec1
Matlab lec1
Amba Research
 
MATLAB - Arrays and Matrices
MATLAB - Arrays and Matrices
Shameer Ahmed Koya
 
Jumping statements
Jumping statements
Suneel Dogra
 
Matlab time series example
Matlab time series example
Ovie Uddin Ovie Uddin
 
Introduction to Matlab Scripts
Introduction to Matlab Scripts
Shameer Ahmed Koya
 
Circuit analysis i with matlab computing and simulink sim powersystems modeling
Circuit analysis i with matlab computing and simulink sim powersystems modeling
Indra S Wahyudi
 
Do While and While Loop
Do While and While Loop
Hock Leng PUAH
 
Cruise control simulation using matlab
Cruise control simulation using matlab
Hira Shaukat
 
Reduction of multiple subsystem [compatibility mode]
Reduction of multiple subsystem [compatibility mode]
azroyyazid
 
Polynomials and Curve Fitting in MATLAB
Polynomials and Curve Fitting in MATLAB
Shameer Ahmed Koya
 
While , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
MATLAB Programming - Loop Control Part 2
MATLAB Programming - Loop Control Part 2
Shameer Ahmed Koya
 
Anonymous and Inline Functions in MATLAB
Anonymous and Inline Functions in MATLAB
Shameer Ahmed Koya
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2
Shameer Ahmed Koya
 
User defined Functions in MATLAB Part 1
User defined Functions in MATLAB Part 1
Shameer Ahmed Koya
 
User Defined Functions in MATLAB Part-4
User Defined Functions in MATLAB Part-4
Shameer Ahmed Koya
 
Abstract Class Presentation
Abstract Class Presentation
tigerwarn
 
Mat lab workshop
Mat lab workshop
Vinay Kumar
 
Jumping statements
Jumping statements
Suneel Dogra
 
Introduction to Matlab Scripts
Introduction to Matlab Scripts
Shameer Ahmed Koya
 
Circuit analysis i with matlab computing and simulink sim powersystems modeling
Circuit analysis i with matlab computing and simulink sim powersystems modeling
Indra S Wahyudi
 
Do While and While Loop
Do While and While Loop
Hock Leng PUAH
 
Cruise control simulation using matlab
Cruise control simulation using matlab
Hira Shaukat
 
Reduction of multiple subsystem [compatibility mode]
Reduction of multiple subsystem [compatibility mode]
azroyyazid
 
Polynomials and Curve Fitting in MATLAB
Polynomials and Curve Fitting in MATLAB
Shameer Ahmed Koya
 
While , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
Ad

Similar to Matlab Script - Loop Control (20)

Loops in c language
Loops in c language
tanmaymodi4
 
Loops in c language
Loops in c language
Tanmay Modi
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
eShikshak
 
Iteration
Iteration
Liam Dunphy
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
Béo Tú
 
Loops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
REHAN IJAZ
 
Java căn bản - Chapter6
Java căn bản - Chapter6
Vince Vo
 
Loop and while Loop
Loop and while Loop
JayBhavsar68
 
Ch6 Loops
Ch6 Loops
SzeChingChen
 
Iterations FOR LOOP AND WHILE LOOP .pptx
Iterations FOR LOOP AND WHILE LOOP .pptx
VijayaLakshmi948042
 
Programming Fundamentals presentation slide
Programming Fundamentals presentation slide
mibrahim020205
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Priyom Majumder
 
C++ control structure
C++ control structure
bluejayjunior
 
Loops c++
Loops c++
Shivani Singh
 
Loops
Loops
SAMYAKKHADSE
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
NaumanRasheed11
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
Muhammad Hammad Waseem
 
Lecture 4
Lecture 4
Mohammed Khan
 
Loops in c language
Loops in c language
tanmaymodi4
 
Loops in c language
Loops in c language
Tanmay Modi
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
eShikshak
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
Béo Tú
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
REHAN IJAZ
 
Java căn bản - Chapter6
Java căn bản - Chapter6
Vince Vo
 
Loop and while Loop
Loop and while Loop
JayBhavsar68
 
Iterations FOR LOOP AND WHILE LOOP .pptx
Iterations FOR LOOP AND WHILE LOOP .pptx
VijayaLakshmi948042
 
Programming Fundamentals presentation slide
Programming Fundamentals presentation slide
mibrahim020205
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Priyom Majumder
 
C++ control structure
C++ control structure
bluejayjunior
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
NaumanRasheed11
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Ad

Recently uploaded (20)

LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 

Matlab Script - Loop Control

  • 2. INTRODUCTION In this lecture we will discuss about another flow control method – Loop control. A loop control is used to execute a set of commands repeatedly The set of commands is called the body of the loop MATLAB has two loop control techniques 1. Counted loops - executes commands a specified number of times 2. Conditional loops - executes commands as long as a specified expression is true 2 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 3. INTRODUCTION …. • Counted loops are called ‘for’ loop • Conditional loops are called ‘while’ loop • Both Scripts and functions also allow to loop using for and while loops. • The keyword “end” is used to show the end of a Loop • In while loops the Code for each condition is separated by the keyword “end” 3 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 4. FOR LOOP SYNTAX for varname = min:max statements end 4 N=10; for I = 1:N A(I) = 1/(I+J-1); end for j=1:10 Statements done e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 5. 5 WHILE LOOP SYNTAX while I<N computations done change I Initialize I, N I=1; N=10; while I<=N A(I)=1/(I+1); I=I+1; end while condition is true statements end e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 6. 6 FOR VS WHILE FOR Repeats for specified number of times ALWAYS executes computation loop at least once!!! Can use + or – increments Can escape (BREAK) out of computational loop WHILE Will do computational loop ONLY if while condition is met Be careful to initialize while variable Can loop forever if while variable is not updated within loop!!! e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 7. THE FOR LOOP Other Forms 7 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 8. THE FOR LOOP … • Matlab creates vector from 1 with an increment of 1,([ 1 2 … 10]), and execute the commands for each value of ii. • Matlab creates a vector with an increment of 2, as [ 1 3 5 …9],and execute the commands for each value of ii. • Here the values of ii are defined by user as [5 9 7]. The commands are executed for these specific values. • Here the increment is negative 8 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 9. FOR LOOP EXAMPLES 1. A program to print the numbers from 1 to 10 for i=1:10 disp(i) end 2. A program to calculate the sum of squares of numbers from 1 to n. n=input('plz enter the no: '); s=0; for i=1:n s=s+i^2; end disp(s) 9 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 10. FOR LOOP EXAMPLES 3. Calculate the factorial of any number n n=input ('enter any integer '); f=1; for i=1: n f=f*i; end disp(f) 4. Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x), if ( x(ii) > 0 ), count = count + 1; end end fprintf('Number of positive numbers is %dn', count); 10 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 11. FOR LOOP ELECTRICAL ENGINEERING APPLICATION Where Vci is the initial capacitor voltage; Vcf is the voltage the capacitor will reach if it charges for an infinite amount of time. 11 Plot the switching response of a given RC circuit          msforteVVV mstforV tV RCtt cfcicf ci c 5.1)( 5.10 /)( 0 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 12. FOR LOOP ELECTRICAL ENGINEERING APPLICATION … Vci = input('Enter initial capacitor voltage, Vci: '); Vcf = input('Enter Final capacitor voltage, Vcf: '); R = input('Enter Resistance value, R: '); C = input('Enter Capacitance value, C: '); t0 = input('Enter Switching time, t0: '); tf = input('Enter Simulation end time, tf: '); t=linspace(0,tf,1000); Vc=zeros(1,1000); for i=1:1000 if t(i)<t0 Vc(i)=Vci; else Vc(i)=Vcf+(Vci-Vcf)*exp(-(t(i)- t0)/(R*C)); end end plot(t*1000,Vc); title('RC Step Response') ylabel('Capacitor voltage') xlabel('time in msec') grid on 12 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 13. THE WHILE LOOP • The while- loop used when the number of loop iterations is unknown • Number of iteration is controlled by a condition. • We can test the condition in each iteration and stop looping when it is false. • For example, • Keep reading data from a file until you reach the end of the file • Keep adding terms to a sum until the difference of the last two terms is less than a certain amount. e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m 13
  • 14. 1. Loop evaluate conditional expression 2. If conditional-expression is true, executes code in body, then goes back to Step 1 3. If conditional-expression is false, skips the body and goes to code after end-statement Note: Body of loop must change value of variable There must be some value of the variable that makes the conditional expression be false 14 THE WHILE LOOP … e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 15. INFINITE LOOP If the conditional expression never becomes false, the loop will keep executing... forever! This condition is called as an infinite loop. This can happen in different ways • No proper condition statement • The condition variable is not updated in the body of loop If your program gets caught in an infinite loop, Press CTRL+C 15 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 16. WHILE LOOP EXAMPLES 1. A program to print the numbers from 1 to 10 i = 1; while i<=10 disp(i) i = i +1 end 2. A program to display powers of 2. x = 1 while x <= 15 x = 2*x end 16 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m
  • 17. WHILE LOOP EXAMPLES … 3. Program ask the user to input a number between 1 and 10 value = input ('Please Enter a Number betwee n 1 and 10 (1-10)'); while ( value < 1 || value > 10) fprintf('Incorrect input, please try again .n'); value = input ('Enter a Number between 1 a nd 10 (1-10)'); end 17 e l e c t r i c a l e n g g t u t o r i a l . b l o g s p o t . c o m