Umal-qura university



Yüklə 0,73 Mb.
səhifə12/30
tarix23.12.2023
ölçüsü0,73 Mb.
#156716
1   ...   8   9   10   11   12   13   14   15   ...   30
Signal and Systems Manual - v2full

Looping constructs




        1. For Loop : A for loop is a construction of the form

for i= 1 : n
end
This will repeat
once for each index value i = 1, 2 n. Here are some examples of
MATLAB's for loop capabilities:


Example: The basic for loop
>> for i = 1 : 5
c = 2*i
end
c =
2
..... lines of output removed ... c =
10
computes and prints "c = 2*i" for i = 1, 2, ... 5.


Example: For looping constructs may be nested. Here is an example of creating a matrix content inside a nested for loop:
>> for i = 1:10
for j = 1:10
A(i, j) = i / j;
end
end
There are actually two loops here, with one nested inside the other; they define A(1,1), A(1,2), A(1,3) ... A(1,10), A(2,1), A(2,2) ... A(2,10), ... A(10,1), A(10,2) ... A(10,10)
in that order.
Example: MATLAB will allow you to put any vector in place of the vector 1:n in this construction. Thus the construction
>> for i = [2,4,5,6,10]


end
is perfectly legitimate.
In this case program will execute 5 times and the values for the variable i during execution are successively, 2, 4, 5, 6, 10.

-------------------------TASK 05--------------------------


Using for loop, generate the cube of the first ten integers.



        1. While Loops

A while loop is a construction of the form
while
end
where condition is a MATLAB function, as with the branching construction. The program will execute successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is no guarantee in general that you will exit a while loop. Here is a sample program using a while loop.
Example:
function l = twolog(n)
% l = twolog(n). l is the floor of the base 2
% logarithm of n.
l = 0;
m = 2;
while m<=n
l=l+1; m=2*m;
end

Yüklə 0,73 Mb.

Dostları ilə paylaş:
1   ...   8   9   10   11   12   13   14   15   ...   30




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə