ENGINEERING COURSES FOR UNDERGRADUATE STUDENTS

LECTURES & APPLICATIONS
 
HomeHome  CalendarCalendar  FAQFAQ  SearchSearch  MemberlistMemberlist  UsergroupsUsergroups  RegisterRegister  Log inLog in  

Share | 
 

 LOOPS AND CONTROL

Go down 
AuthorMessage
Eng.Saeed Almalowi



Posts : 38
Join date : 2009-10-27
Location : UNITED STATE OF AMERICA, STATE COLLEGE,PA

PostSubject: LOOPS AND CONTROL   Thu Oct 29, 2009 6:53 am

Sometimes, you do need to use some kind of loop to do what you need, rather than just operating on an entire matrix or vector at once.

While Loops
The syntax for a while loop is

while (some logical expression)
do something;
do something else;
end

To keep this from going on forever, you should probably be changing some variable in the logical expression within the body of the loop so that it eventually is not true.

For
The syntax for a for loop is:

FOR X = 1:N,
A(X) = 1/(2+X-1);
END

You should try to avoid using i and j as counters, since you will wind up redefining i (which is intially defined as the imaginary i.)

If
The syntax for an if statement is

if (logical expression)
matlab command
elseif (other logical expression)
another matlab command
else
a matlab command
end

(You don't need an elseif or an else, but you do need an end.)

break
The break command breaks you out of the innermost for or while loop you are in.

In the process of a loop, if you define an element of an vector that doesn't exist yet (the vector is smaller than the element you're trying to assign), matlab will increase the size of the vector or matrix to allow for the new element to go where you've specified. However, if you know that you're going to be assigning elements until the matrix grows to be some specific size, it's better to "preallocate" the matrix by defining it to be all zeros initially.

matrix = zeros(rows,columns);

will do that.

Examples of some loops are in the file fors.m in the 2.670 Examples directory. (

type fors.m
Back to top Go down
View user profile http://www.aalhameed1.net
 
LOOPS AND CONTROL
Back to top 
Page 1 of 1
 Similar topics
-
» CONTROL COMMISSION FOR GERMANY
» Jinggoy wants to probe DOTC's P4B contract for air traffic control system
» Topamax and birth control
» car spinning out of control
» Inside a bus that is spinning and out of control

Permissions in this forum:You cannot reply to topics in this forum
ENGINEERING COURSES FOR UNDERGRADUATE STUDENTS :: ENGINEERING PROGRAMS/SOFT WARE :: MATLAB PROGRAM FORUM-
Jump to: