Loops in Matlab
Loops in Matlab
Energy Systems
ES 810
When the file is run, MATLAB reads the commands and executes them exactly as it
would if you had typed each command sequentially at the MATLAB prompt.
All m-file names must end with the extension '.m' (e.g. test.m).
If you create a new m-file with the same name as an existing m-file, MATLAB will
choose the one which appears first in the path order (type help path in the command
window for more information).
To make things easier, choose a name for your m-file which doesn't already exist.
To save the m-file, simply go to the File menu and choose Save (remember to
save it with the '.m' extension). To open an existing m-file, go to the File menu
and choose Open.
Rules:
• The variables in the expression to be tested must have values assigned prior to
entering the IF statement.
• The block of code will only execute if the expression is true. If the
expression is false, then the code is ignored.
• Values assigned to the variables used in the expression may be changed in the
block of code inside the IF statement
Conditions And Loops in MATLAB if Loop
a = 2;
b = 3;
if (a<b)
j = -1;
end
Additional statements can be added for more refined decision making
a = 4; b = 3;
if (a<b)
j = -1;
elseif (a>b)
j = 2;
end
Conditions And Loops in MATLAB if Loop
Conditions And Loops in MATLAB if Loop
x = 100;
y = -10;
if x < 50 % to see if x is less than 50
z = x – y^2;
A = x + 12.5*y + z^3;
end
% won’t run because x is not less than 50
Conditions And Loops in MATLAB for Loop
'for' loops
Purpose:
To repeat a statement or a group of statements for a fixed number of
times.
Format:
for variable = expression
statement(s) to be executed (know as the body of the loop)
end
Conditions And Loops in MATLAB for Loop
Examples:
Sequential numbers
for i=1:3 %executes three times
x=i^2
end
x=
1
x=
4
x=
9
Example
y = -10;
x=1:1:100
z=x-y
A=x+12.5+z3 for x<50
z= = x-y+2
A = x + 12.5*y + z2 for x=>50
Practice Exercise to format the loops (if and for)
Reynold Number, Nusselt Number and Heat transfer Coefficient
v=1.568*10^-5;%Viscosity of air @40C
Vm=2 m/s
Dia of the pipe is 2cm or 0.002 m
Length of the pipe =L= 5 m
n=0.4
For circular tubes and constant heat flux (especially for solar radiations)
Reynolds number (Re) is a dimensionless number that gives a measure of the ratio of
inertial forces to viscous forces