If Statement
If Statement
If x < 1
X is less then 1;
End
If x = 0
Turn off the fan;
End
If x = 1
Turn on the fan;
End
If / else statement:
If / else statement is also a condition statement. We use it for two information
in one time or one condition. If we need some information in a condition but
also we need some other information against that condition if the first
condition will false then we use if / else statement.
Syntax:
If condition
Command1
Else
Command 2
End
Programs:
If name == “shah fahad”
Unlock the system;
else
“ you are wrong person”;
End
If x == 1
“The number is one”;
else
“the number is not one”;
If / else if statement:
if / else if statement is a conditions statement, which is use for multiple
condition at a time. If we need multiple information from computer in the
base of conditions we use if / else if statement.
Syntax:
If condition 1
Commands 1
Elseif condition 2
Commands 2
Else
Commands 3
End
Programs:
If name == “shah fahad”
“you are civil department student”;
elseif name == “ Hamza”
“you are fsc student”;
elseif name == “junaid”
“you are electrical department student”;
else
“not in record”;
End
If x > 1
y = x – 5;
elseif x < 6
y = x + 5;
else
y = 0;
end
Switch statement:
Switch statement is also use for condition. Its work almost the same as if/
elseif statement. In some places we use switch statement instead of if/elseif
statement for time consuming it take less time than if/elseif statement.
Syntax:
Switch expression
Case1 expression 1
Case2 expression 2
Otherwise
End
Programs:
Switch A
Case “hi”
Msgbox(“he says hi”)
Case “ bye”
Msgbox(“he says bye”)
Otherwise
Msgbox(nothing)
End
For loop:
Use for a known number of iterations. It make command to execute
repeatedly.
Matlab syntax:
For n = 1 : 100
Commands
End
The loop variable:
Is defined as a vector
Is a scalar within the command block
Does not have to have consecutive values but cleaner if they are consecutive
Programs:
Forii = 1:1:25
A(ii) = [ii,ii^2];
End
Nested for loop
Forii = 1:1:25
Forii = [1 3 5 6]
A(ii) = ii*ii;
End
End
While loop:
The while is like a more general for loop: don’t need to Know number of
iterations
Syntex:
While condition
Commands
End
The command block will execute while the conditional expression is true. It is a
loop but it is a conditional loop.
Beware of indefinite loops.
Problems:
n = 1;
Y = zeros(1,10);
While n <= 10
Y(n) = 2*n/(n+1);
n = n+1;
end
x = 1;
while x
% execute statements
End
X = 1;
While (x^<10)
y = x^2;
plot(x,y,z’or’); hold on
x = x+1;
end