Operations Research I: Matlab Lab 02
Operations Research I: Matlab Lab 02
Research I
MATLAB Lab 02
INS TRUCTOR: DR. OSWALDO AGUIRRE
COURS E : IE 3390
S E MESTER: FALL 2019
Logic Commands
Decisions:
If
If elseif
Switch
Loops
For loop
While
If statement
Use double equal sing
to compare two values
If Syntax
if value = = condition yes
condition instructions
instructions
else
No
instructions
instructions
end
Logical operators
Operation Description
== equal
~= Not equal
> greater than
>= Greater and equal than
< Less than
<= Lesser or equal than
&& AND
|| OR
If Example
Example: Create a MATLAB script that analyze the value of variable a
and tell to the user if the value is positive or negative
◦ Evaluate the value of variable a
◦ If a <0 write negative
◦ If a>= 0 write positive yes
a<0 ‘negative’
a=-1
if a<0 No
'negative'
‘positive’
else
'positive'
end
If with more than one
condition
Calculate the square of a number if the value of a number is between 10 and 15
yes
If elseif
Condition
yes
1 instructions
No
Condition yes
2 instructions
No
instructions
If esleif Example
Compare if the value of variable “a” is between 10 and 100
Tell the user
if the value is with in range
Below range
Above range
If esleif Example
a>10 &&
yes
a<100
Within range
No
yes
a<10
Below range
No
above
a=101
if a>10 && a<100
'within range'
elseif a<10
'below range'
else
'above range'
end
Switch
Switch among several cases
If yes
a==1
0
If yes
a==2
other yes
wise
Switch example
Create a program that check the value of the variable option and make the
following decisions
Option =1
c=a+b
Option =2
c=a-b
Option =3
c=a*b
Option =4
c=a/b
Otherwise
c=0
Switch example
Create a program that check the %Switch example
value of the variable option and
make the following decisions a=4
b=2
option=0
Option =1
switch (option)
c=a+b
case {1}
Option =2 c=a+b
c=a-b case {2}
Option =3 c=a-b
c=a*b case {3}
Option =4 c=a*b
case {4}
c=a/b
c=a/b
Otherwise
otherwise
c=0
c=0
end
Exercise #01
Write a MATLAB script
%Loop example
a=1
b=2
for i=1:10 Variable i = 1 to 10
c=a+b
end
%Loop example
a=1
b=2
This instruction will
for i=1:10
be repeated until the
c=a+b
value of the variable i
end
is between 1 and 10
At this point MATLAB
update the value of
the for loop variable
in this case i
Use for loop variables inside
the loop
Show the variables of the for loop variable
for (i=1:5)
i
end
Example
Multiply by two the numbers of a vector a and save
the result in vector c using a for loop
a= 2 8 5 4
example
%loop Example 2
a=[2,8,5,4]
c=zeros(1,4) % create variable z with size 1 x 4 with
zeros inside
for index=1:4
c(1,index)=a(1,index)*2
end
While loop
Syntax
While condition== true
Instructions
end
𝜆 K h
600 8 .2*.3
600 8 .2*.29
600 8 .2*.28
Exercise 04
Write a MATLAB script to obtain the larger value in a vector using a for
loop and if
Do NOT use the max function
Exercise 05
Write a MATLAB script that generates a value from 1 to 5
Help the user telling if the user need to try a bigger or smaller number