<< Chapter < Page | Chapter >> Page > |
MATLAB has control statements like those in most computer languages. We will only study theloop here. See the MATLAB manual
for details onandstatements.
while
What for loops do is allow a statement or a group of statements to be repeated. For example,
assigns the value 0 to the firstelements of the array. Ifis less than 1,
the instruction is still valid but nothing will be done. Ifis not defined, then
the following message will appear:
n
Ifcontains a real value, the integer part ofis used. Ifis a complex
number, the integer part of the real part is taken. (This should, however, beavoided.) Ifis not declared earlier or is of smaller dimension than, then
extra memory is allocated.
n
The command end must follow the command for. If it is not present, MATLAB will wait for remaining statements until you type t he command end, and nothing will be executed in the meantime.
More than one statement may be included in the loop. The statementis the way to specify all the integer values between 1 and. A
step different than 1 may be specified. For example, the statementis equivalent to. Negative steps
are also allowed, as in.
i=n:-1:1
We may use aloop to draw a circle of radius 1. Type
for
Note how easy it is to plot a curve. But also note how slowly the for loop
is executed. MATLAB is not very good at executing things one by one. Itprefers, by far, a vector-oriented statement. Using the range specification as
in theloop, it is possible to speed up the process by replacing the explicitloop by an implicitloop using the colon, like this:
for
Note how much faster this command is executed. In general,loops should
be avoided as much as possible. For example, the firstloop you typed
could have been replaced by the command, which is much
more efficient. The functionfills the variable with 0's to the specified
size. Similarly, the functionfills the variable with 1's. The size can also
be determined by the size of the argument. Ifis a matrix of size, then
the commandfills the matrixwith 1's and forces the matrixto have exactly the same size as the matrix.
A
AvoidingLoops.
for
Sinceloops are very inefficient in MATLAB
(they are computed sequentially, adding several more computations for everyloop), it is preferable to use the matrix capabilities of MATLAB to replaceloops and speed up processing time.
for
x = [1 2 3 4 5 6 7 8 9 10]
x = [z 2*z 3*z ... 10*z]
x = [z z**2 z**3 ... z**10]
x = [exp(0) exp(j*4*pi/100) ... exp(j*200*pi/100)]
Notification Switch
Would you like to follow the 'A first course in electrical and computer engineering' conversation and receive update notifications?