Chapter5 - For Loops - v2
Chapter5 - For Loops - v2
In for loops
we ask MATLAB to execute a block of
code for all values in a certain vector
Usually used to execute a block of code
for a certain number of times
impleForLoop
>> SimpleForLoop
Workspace
index
1
impleForLoop
>> SimpleForLoop
1
Workspace
index
1
impleForLoop
>> SimpleForLoop
1
Workspace
index
2
impleForLoop
>> SimpleForLoop
1
2
Workspace
index
2
impleForLoop
>> SimpleForLoop
1
2
Workspace
index
3
impleForLoop
>> SimpleForLoop
1
2
3
Workspace
index
3
impleForLoop
>> SimpleForLoop
1
2
3
Workspace
index
4
impleForLoop
>> SimpleForLoop
1
2
3
4
Workspace
index
4
Implied increment of 1
Values of k : 1 2 3 4
real number increment
Values of k: 2 2.5 3
Negative increment
Values of k: 0 -2 -4 -6
for k= 1:n
% print the greeting
disp('Welcome Huskies')
end
Example 3
Calculate the average of 4 numbers given by the user
ear
% Average 4 numbers from user input
n= 4; % number of data values
total = 0;;
for k= 1:n
Another way !
Save the values entered by the user in a
vector of values then use the built in
function mean() !
The loop
is usedfrom
to read
values
%
Average
4 numbers
user the
input
n= 4; % initialize the number of data values
numbers = [];
for k= 1:n
% read and save input value
17
Genes
Find genes with expression
level
>= 10 and output their
IDs
12104
37990
11410
34412
41319
28671
25443
GenesIDs
Demo on MATLAB
190.2
5204.3
25.1
7.7
799.4
6.0
940.9
GeneExp
A
sqrtA
Big Mess!!