5 views

Original Title: h

Uploaded by Dulanga Fernando

- Loops
- Brian Evans - Arduino Programming Notebook
- LabVIEW Tutorial Session 2
- GML
- Computer Programming Data Structures
- Loops in C Programming
- Py4inf 05 Iterations
- Arduino Programming Notebook
- Converting to Page at a Time Subfiles
- Revision on MATLAB & Image Processing With Matlab
- Programmers_Reference_Manual.pdf
- Examenes Clad Ingles
- Unit 3 Test (Ch 4 5 6) 11-6-2013 KEY
- jBASE_Programmers_Reference_Manual.pdf
- Control Statement
- Flow Control
- Jacobi Iterative Method in Matlab - MATLAB Answers - MATLAB Central
- Array and Cluster Data Type
- Parallel Mat Lab
- P12 - Iterations

You are on page 1of 9

In this tutorial we will demonstrate how the for and the while loop are used. First, the for

loop is discussed with examples for row operations on matrices and for Eulers Method

to approximate an ODE. Following the for loop , a demonstration of the while loop is

given.

We will assume that you know how to create vectors and matrices and know how to

index into them. For more information on those topics see one of our tutorials on either

vectors (Introduction to Vectors in Matlab), matrices (Introduction to Matrices in Matlab),

or vector operations ((Vector Functions).

1. For Loops

2. While Loops

For Loops

The for loop allows us to repeat certain commands. If you want to repeat some action in

a predetermined way, you can use the for loop. All of the loop structures in matlab are

started with a keyword such as for, or while and they all end with the word end. Another

deep thought, eh.

The for loop is written around some set of statements, and you must tell Matlab where

to start and where to end. Basically, you give a vector in the for statement, and Matlab

will loop through for each value in the vector:

For example, a simple loop will go around four times each time changing a loop

variable, j:

>> for j=1:4,

j

end

j =

1

j =

2

j =

3

j =

4

>>

When Matlab reads the for statement it constructs a vector, [1:4], and j will take on each

value within the vector in order. Once Matlab reads the end statement, it will execute

and repeat the loop. Each time the for statement will update the value of j and repeat

the statements within the loop. In this example it will print out the value of j each time.

For another example, we define a vector and later change the entries. Here we step

though and change each individual entry:

>> v = [1:3:10]

v =

1 4 7 10

>> for j=1:4,

v(j) = j;

end

>> v

v =

1 2 3 4

Note, that this is a simple example and is a nice demonstration to show you how a for

loop works. However, DO NOT DO THIS IN PRACTICE!!!! Matlab is an interpreted

language and looping through a vector like this is the slowest possible way to change a

vector. The notation used in the first statement is much faster than the loop.

A better example, is one in which we want to perform operations on the rows of a

matrix. If you want to start at the second row of a matrix and subtract the previous row

of the matrix and then repeat this operation on the following rows, a for loop can do this

in short order:

>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']

A =

1 3 2

2 2 1

3 1 3

>> B = A;

>> for j=2:3,

A(j,:) = A(j,:) - A(j-1,:)

end

A =

1 3 2

1 -1 -1

3 1 3

A =

1 3 2

1 -1 -1

2 2 4

For a more realistic example, since we can now use loops and perform row operations

on a matrix, Gaussian Elimination can be performed using only two loops and one

statement:

>> for j=2:3,

for i=j:3,

B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)

end

end

B =

1 3 2

0 -4 -3

3 1 3

B =

1 3 2

0 -4 -3

0 -8 -3

B =

1 3 2

0 -4 -3

0 0 3

Another example where loops come in handy is the approximation of differential

equations. The following example approximates the D.E. y=x^2-y^2, y(0)=1, using

Eulers Method. First, the step size, h, is defined. Once done, the grid points are found,

and an approximation is found. The approximation is simply a vector, y, in which the

entry y(j) is the approximation at x(j).

>> h = 0.1;

>> x = [0:h:2];

>> y = 0*x;

>> y(1) = 1;

>> size(x)

ans =

1 21

>> for i=2:21,

y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);

end

>> plot(x,y)

>> plot(x,y,'go')

>> plot(x,y,'go',x,y)

While Loops

If you dont like the for loop , you can also use a while loop . The while loop repeats a

sequence of commands as long as some condition is met. This can make for a more

efficient algorithm. In the previous example the number of time steps to make may be

much larger than 20. In such a case the for loop can use up a lot of memory just

creating the vector used for the index. A better way of implementing the algorithm is to

repeat the same operations but only as long as the number of steps taken is below

some threshold. In this example the D.E. y=x-|y|, y(0)=1, is approximated using Eulers

Method:

>> h = 0.001;

>> x = [0:h:2];

>> y = 0*x;

>> y(1) = 1;

>> i = 1;

>> size(x)

ans =

1 2001

>> max(size(x))

ans =

2001

>> while(i<max(size(x)))

y(i+1) = y(i) + h*(x(i)-abs(y(i)));

i = i + 1;

end

>> plot(x,y,'go')

>> plot(x,y)

- LoopsUploaded byKyci Petrov
- Brian Evans - Arduino Programming NotebookUploaded byFelipeZ64
- LabVIEW Tutorial Session 2Uploaded byMohammed Al-abide
- GMLUploaded byJeter Dos Santos Campos
- Computer Programming Data StructuresUploaded byBeing Manish
- Py4inf 05 IterationsUploaded byIjazKhan
- Arduino Programming NotebookUploaded byJoão Francisco
- Converting to Page at a Time SubfilesUploaded byrachmat99
- Loops in C ProgrammingUploaded byShyamal Chandra
- Revision on MATLAB & Image Processing With MatlabUploaded byHesham Fadl-Allah Mohamad
- Programmers_Reference_Manual.pdfUploaded byAlejandro
- Examenes Clad InglesUploaded byGerardo Grijalva Avila
- Unit 3 Test (Ch 4 5 6) 11-6-2013 KEYUploaded byOsama Maher
- jBASE_Programmers_Reference_Manual.pdfUploaded bytujthevux
- Control StatementUploaded byaslinayaya
- Flow ControlUploaded byrahul rastogi
- Jacobi Iterative Method in Matlab - MATLAB Answers - MATLAB CentralUploaded byamit rahul
- Array and Cluster Data TypeUploaded bysuneerav17
- Parallel Mat LabUploaded byjeovanevs
- P12 - IterationsUploaded bysullivan583
- Chapter 6Uploaded bylalitha
- jawaharlal subhashUploaded byRahul Kulshrestha
- Lecture 6Uploaded byJim Demitriyev
- Unit5 Flowofcontrol 140915235226 Phpap01Uploaded byAnsh Ganatra
- Controlling Sequence Computer programmingUploaded bygideon tinio
- ForUploaded byKenver Regis
- NA fileUploaded byRishi1986
- Pre Release OL Nov15 Final BBycotUploaded byPooja Soorjonowa-Fowdar
- [Developer Shed Network] Server Side - PHP - PHP 101 (Part 3) - Chocolate Fudge and Time MachinesUploaded byeminem_b
- TA ZC142-L5Uploaded byrajpd28

- SENI ANYAMANUploaded byauni dalilah
- Lab-01Uploaded byDulanga Fernando
- Introduction to Company McdonaldsUploaded byDulanga Fernando
- Creative Solution Gen 1Uploaded byDulanga Fernando
- Engineers Australia Code of Ethics 2010Uploaded bymatthew1ferreira
- 13 Jan S1Uploaded bykaran408
- New Microsoft Word DocumentUploaded byDulanga Fernando
- How Do We Define a SystemUploaded byDulanga Fernando
- Chemistry Unit 4Uploaded bykrithipisapati
- Monash University ESD GuideUploaded byDulanga Fernando
- ENG Teamwork Team CharterUploaded byDulanga Fernando
- T12a_Oral Presentation Marking (SW) (4)Uploaded byDulanga Fernando
- New Microsoft Word DocumentUploaded byDulanga Fernando
- tUploaded byDulanga Fernando
- OXANEUploaded byDulanga Fernando
- NotesUploaded byDulanga Fernando
- C3 Jan 13 Model RedUploaded byDulanga Fernando
- C4 Jan 13 Model RedUploaded byMiriam Animashaun
- New Microsoft Office Word 97 - 2003 DocumentUploaded byDulanga Fernando
- C4 QuestionsUploaded byDulanga Fernando
- c4 practice questionsUploaded byDulanga Fernando
- New Microsoft Office Word DocumentUploaded byDulanga Fernando
- further mathsUploaded byDulanga Fernando

- LarCalc10_ch01_sec2Uploaded byZachary
- A New Optimization Phase for Scientific Workflow Management SystemsUploaded byShibani Suri
- Number StoryUploaded bybigstrand4476
- Factoring TrinomialsUploaded byRam Singh
- Digital LabmanualUploaded byRaji Sharmi
- UniDesk: TOPdesk as a Shared Service for Higher and Further EducationUploaded byTOPdesk
- Packt.postgreSQL.9.6.High.performance.1784392979Uploaded byCaio Villela
- 52_Discovery of Ranking Fraud for Mobile AppsUploaded bysv
- EE 298 HW1Uploaded byDarvy Ong
- Red Hat GlobalUploaded byChester Connolly
- ds-slm5650AUploaded byIlham Perdana Thamrin
- Learning UnitsUploaded bySurgio Becker
- System Setup Ex SeriesUploaded byWaldon Hendricks
- Komplete Kontrol Setup Guide EnglishUploaded bymuzicoterapie1092
- Conceptual dependency in Artificial intelligenceUploaded byKrishanaKantPareek
- Touchscreen ReportUploaded bymonty
- NetAnalysis-UsingEtherealUploaded by~kdm
- VXvue User Manual for Veterinary Use_V1.1_EN.pdfUploaded byscribangelof
- Tender Document RcsUploaded byAnshika Jain
- A ZEOS Basics Tutorial Not Only for FirebirdUploaded byRolly Ar
- Datasheet_ecosy m 6530cdnUploaded byEdi Purnomo
- 0417_s10_ms_11Uploaded byKassem Farhat
- Iso 9001 ImplementationUploaded bycarloste102
- cfdpreUploaded byHüseyin Cihan Kurtuluş
- Howto Create a GAL FileUploaded byajalles
- Uses of cloves help in making work easier, Health benefits of cloves, लौंग___.txtUploaded bypuneet
- Mcse, Mcsa, Cissp (Pending)Uploaded byali137
- Steps to Fill Online Application FormUploaded byFirdosh Khan
- smcc2011Uploaded bybassalemi
- An Enhancement of User Behavior using Closed Set of Agglomerative Approach with GRC ConstraintUploaded byIJRASETPublications