0% found this document useful (0 votes)
128 views58 pages

Matlab Manual 2020 21 Mechanical

This document provides a manual for using MATLAB software to perform optimization tasks in a lab setting. It introduces MATLAB, describing how to start and quit the program, work in the command window, and use basic mathematical functions. Elementary functions covered include trigonometric, exponential, logarithmic and other common functions. Examples are provided to demonstrate using round, floor, ceil and other functions to perform calculations in MATLAB.

Uploaded by

kishore nandyala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views58 pages

Matlab Manual 2020 21 Mechanical

This document provides a manual for using MATLAB software to perform optimization tasks in a lab setting. It introduces MATLAB, describing how to start and quit the program, work in the command window, and use basic mathematical functions. Elementary functions covered include trigonometric, exponential, logarithmic and other common functions. Examples are provided to demonstrate using round, floor, ceil and other functions to perform calculations in MATLAB.

Uploaded by

kishore nandyala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

MANUAL FOR

OPTIMIZATION LAB
WITH MATLAB
SOFTWARE
Department of Mechanical Engineering

ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES


(AUTONOMOUS)
New Boyanapalle, Rajampet – 516126
Optimization lab with MATLAB software

Department of Mechanical Engineering, AITS, Rajampet. Page 1


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Chapter – I

Fundamentals of Numerical Computing in MATLAB


1.1 Starting and Quitting MATLAB
To start MATLAB click on the MATLAB icon or type in MATLAB, followed by
pressing the enter button or return key at the system prompt. In order to quit MATLAB, type
quit or exit after the prompt, followed by pressing the enter or return key.

Title Window
Menu bar

Current Command Window Workspace


directory Window
window

Start Button Status bar Command


History window
Fig. 1.1: The Default view of MATLAB window

Once the program starts, the MATLAB desktop window opens (Figure 1.1). The window
contains four smaller windows: the Command Window, the Current Directory Window, the
Workspace Window, and the Command History Window.

Department of Mechanical Engineering, AITS, Rajampet. Page 2


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Table: 1.1 MATLAB Windows

Window Purpose
Command Window Main window, enters variables, runs programs.
Workspace Window Provides information about the variables that are used.
Command History Window Logs commands entered in the Command Window.
Current Folder Window Shows the files in the current folder.
Help Window Provides help information
Editor Window Creates and debugs script and function files.
Figure Window Contains output from graphic commands.

1.2 Working in the Command Window


The Command Window is MATLAB’s main window and can be used for executing commands,
opening other windows, running programs written by the user, and managing the software. An
example of the Command Window, with several simple commands is shown in Figure 1.2.

To type a command the


cursor is placed next to
the command prompt
( >> ).

Fig. 1.2: Command Window

Department of Mechanical Engineering, AITS, Rajampet. Page 3


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Notes for working in the Command Window:


 To type a command the cursor must be placed next to the command prompt ( >> ).
 Once a command is typed and the Enter key is pressed, the command is executed. However,
only the last command is executed. Everything executed previously (that might be still
displayed) is unchanged.
 Several commands can be typed in the same line. This is done by typing a comma between
the commands. When the Enter key is pressed the commands are executed in order from left
to right.
 It is not possible to go back to a previous line that is displayed in the Command Window,
make a correction, and then re-execute the command.
 A previously typed command can be recalled to the command prompt with the up-arrow key
(↑). When the command is displayed at the command prompt, it can be modified if needed
and then executed. The down-arrow key (↓) can be used to move down the list of previously
typed commands.
 If a command is too long to fit in one line, it can be continued to the next line by typing three
periods … (called an ellipsis) and pressing the Enter key. The continuation of the command
is then typed in the new line. The command can continue line after line up to a total of 4,096
characters.

The semicolon (;): When a command is typed in the Command Window and the Enter key is
pressed, the command is executed. Any output that the command generates is displayed in the
Command Window. If a semicolon (;) is typed at the end of a command the output of the
command is not displayed. Typing a semicolon is useful when the result is obvious or known, or
when the output is very large. If several commands are typed in the same line, the output from
any of the commands will not be displayed if a semicolon is typed between the commands
instead of a comma.

Typing (%): When the symbol % (percent) is typed at the beginning of a line, the line is
designated as a comment. This means that when the Enter key is pressed the line is not executed.
The % character followed by text (comment) can also be typed after a command (in the same
line). This has no effect on the execution of the command. Usually there is no need for

Department of Mechanical Engineering, AITS, Rajampet. Page 4


Note: This handout is only for academic use.
Optimization lab with MATLAB software

comments in the Command Window. Comments, however, are frequently used in a program to
add descriptions or to explain the program.

The clc command: The clc command (type clc and press Enter) clears the Command Window.
After working in the Command Window for a while, the display may become very long. Once
the clc command is executed a clear window is displayed. The command does not change
anything that was done before. The up-arrow key can also be used to recall commands that were
typed before.

The Help: MATLAB has a host of built-in functions. For a complete list, refer to MATLAB
user’s guide or refer to the on-line Help. Go to menu bar, Help section to get a new window.

1.3 Elementary Functions:

Some commonly used elementary MATLAB mathematical built-in functions:

Table 1.2: Some elementary Functions

Function Stands for


abs Absolute value
sqrt Square root function
sign Signum function
conj Conjugate of a complex number
imag Imaginary part of a complex number
real Real part of a complex number
angle Phase angle of a Complex number
sin Sine function (in radians)
sind Sine function (in degrees)
cos Cosine function
tan Tangent function
exp Exponential Function
log Natural Logarithm function
log 10 Logarithm base 10
cosh Hyperbolic cosine function
sinh Hyperbolic sine function
tanh Hyperbolic tangent function
acos Inverse cosine
acosh Inverse Hyperbolic cosine
asin Inverse sine
asinh Inverse Hyperbolic sine

Department of Mechanical Engineering, AITS, Rajampet. Page 5


Note: This handout is only for academic use.
Optimization lab with MATLAB software

atan Inverse tan


atanh Inverse Hyperbolic tan
round Round to nearest integer
floor Round towards minus infinity
fix Round towards zero
ceil Round towards plus infinity
rem Remainder after division
factorial Factorial Function

Example for Elementary Functions: while using the elementary functions the function syntax
is function (x) ,where x indicates the value

Solve by using Round, Floor and Ceil


2  (6 / 9  3* 2) / 2  3
Sol:
s=2+round(6/9+3*2)/2-3
s = 2.5000
s=2+floor(6/9+3*2)/2-3
s = 2
s=2+ceil(6/9+3*2)/2-3
s = 2.5000

Department of Mechanical Engineering, AITS, Rajampet. Page 6


Note: This handout is only for academic use.
Optimization lab with MATLAB software

MAT LAB environment behaves like a super-complex calculator. You can enter commands at
the >> command prompt.

For example, type a valid expression

and then press Enter button

Adding Comments:

The percent symbol (%) is used for indicating a comment line. For example

Department of Mechanical Engineering, AITS, Rajampet. Page 7


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Commonly used Operators and special characters

Department of Mechanical Engineering, AITS, Rajampet. Page 8


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Some Examples:

Example 1:
Given the values of a = 2, b=5, c = 6;
Find the values of d = a*b*c ; e = d/a;
f =e +c; g = f – b;

Example 2:
initial velocity = 0, acceleration = 9.81; time = 30; Find Final velocity ?

Example 3: A Trigonometric identity is given by:


𝑥 𝑡𝑎𝑛 𝑥 + 𝑠𝑖𝑛 𝑥
𝐶𝑜𝑠 2 =
2 2 𝑡𝑎𝑛 𝑥
𝜋
Verify that the identity is correct by calculating each side of equation, substituting x = 5

Department of Mechanical Engineering, AITS, Rajampet. Page 9


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Example: 4 Matrix Problems


In MAT LAB, a matrix is created by entering each row as a sequence of space or comma
separated elements, and end of a row is demarcated by a semicolon.

Department of Mechanical Engineering, AITS, Rajampet. Page 10


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Exercise 1

1. Calculate
35.7 𝑋 64− 73
a)
45+ 52
5 37
b) .7 . 62 (93 − 652)
4

2732/3 552
c) (2 + 7)3 + +
2 3

3 3 2733
d) 2 + 7 + + 553/2
2
2. Calculates
37 log(76) 3
a) + √910
73 + 546
4
( √250+ 23)2
b) 43 . 3
𝑒 (45− 3 )
3. Calculate
𝜋
5𝜋 7𝜋 tan( 6 ln 8)
a) 𝑐𝑜𝑠 2 ( ) sin( )2 +
6 8 √7
𝜋
5𝜋 7𝜋 tan( 6 ln 8)
b) cos( )2 𝑆𝑖𝑛2 ( ) + 5
6 8 7.2
4. Define the variable x as x = 13.5. then evaluate
a) 𝑥 3 + 5𝑥 2 − 26.7 𝑥 − 52
√14 𝑥 3
b)
𝑒 3𝑥
c) log|𝑥 2 − 𝑥 3 |
5. Define the variable a, b, c and d as a = 16.9, b = -8.02, c = 68.74 and d =
0.8(ab-c)
Evaluate
𝑎𝑏 (𝑎+𝑑)2
a) 𝑎 +
𝑐 √|𝑎𝑏|
6. Consider two matrices
1 0 1 7 4 2
𝐴 = [ 2 3 4] 𝐵 = [ 3 5 6]
−1 6 7 −1 2 1
Department of Mechanical Engineering, AITS, Rajampet. Page 11
Note: This handout is only for academic use.
Optimization lab with MATLAB software

Using MATLAB determine the following:


a) A + B
b) AB
c) A2
d) AT
e) B-1
f) BTAT
g) A2+B2-AB
h) Determinant of A, determinant of B and determinant of AB.
7. Consider two matrices
1 0 0 13 −15 8
𝐶 = [ 2 3 4] 𝐷 = [ 1 25 9]
−1 6 7 8 70 6
Using MATLAB determine the following:
a) C + D
b) CD
c) C2
d) CT
e) D-1
f) DTCT
g) C2+D2-CD
h) Determinant of C, determinant of D and determinant of CD.
8. Consider two matrices.
4 7
𝐸 = [−5] ; 𝐹 = [ 2 ]
9 −3
a) Determine EF?

Department of Mechanical Engineering, AITS, Rajampet. Page 12


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Chapter - II

Programming in MATLAB – I (logical operators, functions and script files)


2.1 Script Files

So far all the commands were typed in the Command Window and were executed when
the Enter key was pressed. Although every MATLAB command can be executed in this way,
using the Command Window to execute a series of command especially if they are related to
each other (a program) is not convenient and may be difficult or even impossible. The commands
in the Command Window cannot be saved and executed again. In addition, the Command
Window is not interactive. This means that every time the Enter key is pressed only the last
command is executed, and everything executed before is unchanged. If a change or a correction
is needed in a command that was previously executed and the results of this command are used
in commands that follow, all the commands have to be entered and executed again.
A different (better) way of executing commands with MATLAB is first to create a file
with a list of commands (program), save it, and then run (execute) the file. When the file runs,
the commands it contains are executed in the order that they are listed. If needed, the commands
in the file can be corrected or changed and the file can be saved and run again. Files that are used
for this purpose are called script files.
2.2 Creating, Saving and Executing a script file

In MATLAB script files are created and edited in the Editor/Debugger Window. This
window is opened from the Command Window. In the File menu, select New, and then select
Blank M-file Script, as shown below.

 A script file is a sequence of MATLAB commands, also called a program.


 When a script file runs (is executed), MATLAB executes the commands in the order they
are written just as if they were typed in the Command Window.
 When a script file has a command that generates an output (e.g., assignment of a value to
a variable without a semicolon at the end), the output is displayed in the Command
Window.
 Using a script file is convenient because it can be edited (corrected or otherwise changed)
and executed many times.

Department of Mechanical Engineering, AITS, Rajampet. Page 13


Note: This handout is only for academic use.
Optimization lab with MATLAB software

 Script files can be typed and edited in any text editor and then pasted into the MATLAB
editor.
 Script files are also called M-files because the extension .m is used when they are saved.

In MATLAB script files are created and edited in the Editor/Debugger Window. This
window is opened from the Command Window. In the File menu, select New, and then select
Script. An window opens with Editor/Debugger.
Once the window is open, the commands of the script file are typed line by line. MATLAB
automatically numbers a new line every time the Enter key is pressed. The commands can also
be typed in any text editor or word processor program and then copied and pasted in the
Editor/Debugger Window.
Before a script file can be executed it has to be saved. This is done by choosing
Save As... From the File menu, selecting a location and entering a name for the file. When saved,
MATLAB adds the extension .m to the name. The rules for naming a script file follow the rules
of naming a variable (must begin with a letter, can include digits and underscore, no spaces, and
up to 63 characters long). The names of user-defined variables, predefined variables, and
MATLAB commands or functions should not be used as names of script files. The
Editor/Debugger window with program entered is shown below.

Fig. 2.1: Editor/Debugger Window in MATLAB


A script file can be executed either directly from the Editor Window by clicking on the
Run icon or by typing the file name in the Command Window and then pressing the Enter key.
For a file to be executed, MATLAB needs to know where the file is saved. The file will be

Department of Mechanical Engineering, AITS, Rajampet. Page 14


Note: This handout is only for academic use.
Optimization lab with MATLAB software

executed if the folder where the file is saved is the current folder of MATLAB or if the folder is
listed in the search path, as explained next.

If an attempt is made to execute a script file by clicking on the Run icon (in the Editor
Window) when the current folder is not the folder where the script file is saved. The user can
then change the current folder to the folder where the script file is saved, or add it to the search
path. Once two or more different current folders are used in a session, it is possible to switch
from one to another in the Current Folder field in the Command Window. The current folder
can also be changed in the Current Folder Window, which can be opened from the Desktop
menu. The Current Folder can be changed by choosing the drive and folder where the file is
saved.

Fig. 2.2: Current Directory Window in MATLAB

2.3 Functions in MATLAB


A user-defined function is a MATLAB program that is created by the user, saved as a
function file, and then can be used like a built-in function. The function can be a simple, single
mathematical expression or a complicated and involved series of calculations. In many cases it is
actually a subprogram within a computer program. The main feature of a function file is that it
has an input and an output. This means that the calculations in the function file are carried out
using the input data, and the results of the calculations are transferred out of the function file by
the output. The input and the output can be one or several variables, and each can be a scalar,
vector, or an array of any size.

Department of Mechanical Engineering, AITS, Rajampet. Page 15


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Schematically, a function file can be illustrated by:

Input Data Function File Output Data

The first line of a function m-file must be of the following form.


function [output_parameter_list] = function_name(input_parameter_list)

The word “function,” typed in lowercase letters, must be the first word in the function
definition line. On the screen the word function appears in blue. The function name is typed
following the equal sign. The name can be made up of letters, digits, and the underscore
character (the name cannot include a space). It is good practice to avoid names of built-in
functions and names of variables already defined by the user or predefined by MATLAB.
Note: Save the function file with the same name of the function.

Example for cube root function in MATLAB


function cuberoot(x)
cuberoot = (x)^(1/3)
end
Matlab output
cuberoot(8)
cuberoot =
2
Example for function: In this problem defining two inputs and output for multiple inputs.
function [a,b,c,d] = asmd(x,y)
a=x+y
b=x-y
c=x*y
d=x/y
end
Matlab output
asmd(4,3)
a= 7 b= 1 c= 12 d = 1.3333

Department of Mechanical Engineering, AITS, Rajampet. Page 16


Note: This handout is only for academic use.
Optimization lab with MATLAB software

2.4. Relational and Logical operators in MATLAB

A computer program is a sequence of computer commands. In a simple program the


commands are executed one after the other in the order they are typed.

MATLAB provides several tools that can be used to control the flow of a program. It is
obvious that changing the flow of a program requires some kind of decision-making process
within the program. The computer must decide whether to execute the next command or to skip
one or more commands and continue at a different line in the program. The program makes these
decisions by comparing values of variables. This is done by using relational and logical
operators,

Relational operators

Relational operator Description


< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
= = (two equal = signs with no space) Equal to
~= Not equal to

 Relational operators are used as arithmetic operators within a mathematical expression.


The result can be used in other mathematical operations, in addressing arrays, and
together with other MATLAB commands (e.g., if) to control the flow of a program.
 When two numbers are compared, the result is 1 (logical true) if the comparison,
according to the relational operator, is true, and 0 (logical false) if the comparison is
false.
 If two scalars are compared, the result is a scalar 1 or 0. If two arrays are compared (only
arrays of the same size can be compared), the comparison is done element-by-element,
and the result is a logical array of the same size with 1s and 0s according to the outcome
of the comparison at each address.
 If a scalar is compared with an array, the scalar is compared with every element of the
array, and the result is a logical array with 1s and 0s according to the outcome of the
comparison of each element.

Department of Mechanical Engineering, AITS, Rajampet. Page 17


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Department of Mechanical Engineering, AITS, Rajampet. Page 18


Note: This handout is only for academic use.
Optimization lab with MATLAB software

The results of a relational operation with vectors, which are vectors with 0s and 1s, are called
logical vectors and can be used for addressing vectors. When a logical vector is used for
addressing another vector, it extracts from that vector the elements in the positions where the
logical vector has 1s.
The example follows

 Numerical vectors and arrays with the numbers 0s and 1s are not the same as logical
vectors and arrays with 0s and 1s. Numerical vectors and arrays cannot be used for
addressing. Logical vectors and arrays, however, can be used in arithmetic operations.
The first time a logical vector or an array is used in arithmetic operations it is changed to
a numerical vector or array.
 Order of precedence: In a mathematical expression that includes relational and arithmetic
operations, the arithmetic operations (+, –, *, /, \) have precedence over relational
operations. The relational operators themselves have equal precedence and are evaluated
from left to right. Parentheses can be used to alter the order of precedence.

Department of Mechanical Engineering, AITS, Rajampet. Page 19


Note: This handout is only for academic use.
Optimization lab with MATLAB software

2.5 Logical Operators


Logical Operator Name Description
Operates on two operands (A and B). If both are
& AND true, the result is true (1); otherwise the result is
false (0).
Operates on two operands (A and B). If either
| OR one, or both, are true, the result is true (1);
otherwise (both are false) the result is false (0).
Operates on one operand (A). Gives the opposite
~ NOT of the operand; true (1) if the operand is false, and
false (0) if the operand is true.

 Logical operators have numbers as operands. A nonzero number is true, and a zero
number is false.
 Logical operators (like relational operators) are used as arithmetic operators within a
mathematical expression. The result can be used in other mathematical operations, in
addressing arrays, and together with other MATLAB commands (e.g., if) to control the
flow of a program.
 Logical operators (like relational operators) can be used with scalars and arrays.
 The logical operations AND and OR can have both operands as scalars, arrays, or one
array and one scalar. If both are scalars, the result is a scalar 0 or 1. If both are arrays,
they must be of the same size and the logical operation is done element-by-element. The
result is an array of the same size with 1s and 0s according to the outcome of the
operation at each position. If one operand is a scalar and the other is an array, the logical
operation is done between the scalar and each of the elements in the array and the
outcome is an array of the same size with 1s and 0s.
 The logical operation NOT has one operand. When it is used with a scalar the outcome is
a scalar 0 or 1. When it is used with an array, the outcome is an array of the same size
with 1s in positions where the array has nonzero numbers and 0s in positions where the
array has 0s.

Department of Mechanical Engineering, AITS, Rajampet. Page 20


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Order of Precedence
Below table shows order of precedence in MATLAB

Department of Mechanical Engineering, AITS, Rajampet. Page 21


Note: This handout is only for academic use.
Optimization lab with MATLAB software

If two or more operations have the same precedence, the expression is executed in order
from left to right.

Department of Mechanical Engineering, AITS, Rajampet. Page 22


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Exercise 2
1. Determine the values of x,y and z for the following set of linear algebraic equations:
𝑥2 − 3 𝑥3 = −5
2𝑥1 + 3𝑥2 − 𝑥3 = 7
4 𝑥1 + 5𝑥2 − 2𝑥3 = 10
2. Solve the following set of equations using MATLAB.
2𝑥1 + 𝑥2 + 𝑥3 − 𝑥4 = 12
𝑥1 + 5𝑥2 − 5𝑥3 + 6𝑥4 = 35
−7𝑥1 + 3 𝑥2 − 7𝑥3 − 5𝑥4 = 7
𝑥1 − 5𝑥2 + 2𝑥3 + 7𝑥4 = 21
3. Evaluate the following expression without using MATLAB. Check the answer with
MATLAB
a) 5 + 3 > 34 /4 b) y = 2 * 3 > 10 / 5 + 1 > 22
b) y = 2 * (3>10/5) + (1>2)2 d) 5 * 3 – 4 * 4 < = ~ 2 * 4 – 2 + ~ 0
4. Write a script file and function to calculate final velocity, the expression is given by
V = U + at
5. Write a function and script file quadratic which accepts three values as the coefficients a,
b and c of quadratic equation, computes and returns the value of the corresponding roots
as x1 and x2.
Equation: 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
√𝑏2 − 4 𝑎𝑐
Roots: 𝑥1 , 𝑥2 = −𝑏 ±
2𝑎
6. Write a script and function file to execute cube root, fourth root, fifth root and Sixth root
for a given value.
7. Let ‘R’ be the radius of a circle. Prepare a script and function file to execute Area and

Perimeter of a circle?

Department of Mechanical Engineering, AITS, Rajampet. Page 23


Note: This handout is only for academic use.
Optimization lab with MATLAB software

CHAPTER - III

Programming in MATLAB – II (conditional statements and loops)

3.1 Conditional Statements


A conditional statement is a command that allows MATLAB to make a decision of
whether to execute a group of commands that follow the conditional statement, or to skip these
commands. In a conditional statement a conditional expression is stated. If the expression is true,
a group of commands that follow the statement are executed. If the expression is false, the
computer skips the group.
The basic form of conditional statement is:

if conditional expression consisting of relational and/or logical operators.

Examples are:
if a < b
if c >= 5
if a == b All the variables must
if a ~= 0 have assigned values.
if (d<h) & (x>7)
if (x~=13) | (y<0)

Conditional statements can be a part of a program written in a script file or a user-defined


function. The if statement is commonly used in three structures, if-end, if-else-end, and if-elseif-
else-end. These are discussed briefly below.

3.2 If – end structure


As the program executes, it reaches the if statement. If the conditional expression in the if
statement is true (1), the program continues to execute the commands that follow the if statement
all the way down to the end statement. If the conditional expression is false (0), the program

Department of Mechanical Engineering, AITS, Rajampet. Page 24


Note: This handout is only for academic use.
Optimization lab with MATLAB software

skips the group of commands between the if and the end, and continues with the commands that
follow the end.

Fig. 3.1 The structure of if-end conditional statement


Example: A worker is paid according to his hourly wage up to 40 hours, and 50% more for
overtime. Write a program in a script file that calculates the pay to a worker. The program asks
the user to enter the number of hours and the hourly wage. The program then displays the pay?
Matlab Progam (m-file)
t = input('Please enter the number of hours worked ');
h = input('Please enter the hourly wage in(rupees) ');
pay = t*h;
if t>40
pay=pay+(t-40)*0.5*h;
end
fprintf('The worker''s pay is (rupees) %5.2f', pay)

Matlab output
Please enter the number of hours worked 50
Please enter the hourly wage in(rupees) 10
The worker's pay is (rupees) 550.00

Department of Mechanical Engineering, AITS, Rajampet. Page 25


Note: This handout is only for academic use.
Optimization lab with MATLAB software

3.3 If – else – end structure


The if-else-end structure provides a means for choosing one group of commands, out of a
possible two groups, for execution.

Fig. 3.2 The structure of if-else-end conditional statement

The first line is an if statement with a conditional expression. If the conditional


expression is true, the program executes group 1 of commands between the if and the else
statements and then skips to the end. If the conditional expression is false, the program skips to
the else and then executes group 2 of commands between the else and the end.
Example: Write a script file for the user is asked to enter three grades, the program calculates the
average of the grades. If the average is less than 60, a message should be displayed “The student
did not pass the course” otherwise a message “The student passed the course”
Matlab Progam (m-file)
score = input('Enter (as a vector) the scores of the three tests
');
avg_grade = (score(1)+score(2)+score(3))/3;
disp('The average grade is: ')
disp(avg_grade)
if avg_grade < 60
disp('The student did not pass the course ')
else
disp('The student passed the course ')

Department of Mechanical Engineering, AITS, Rajampet. Page 26


Note: This handout is only for academic use.
Optimization lab with MATLAB software

end

Matlab output
Enter (as a vector) the scores of the three tests [90 60 75]
The average grade is:
75
The student passed the course

3.4 If-elseif-else-end structure

This structure includes two conditional statements (if and elseif) that make it possible to
select one out of three groups of commands for execution. The first line is an if statement with a
conditional expression. If the conditional expression is true, the program executes group 1 of
commands between the if and the elseif statements and then skips to the end. If the conditional
expression in the if statement is false, the program skips to the elseif statement. If the conditional
expression in the elseif statement is true, the program executes group 2 of commands between
the elseif and the else and then skips to the end. If the conditional expression in the elseif
statement is false, the program skips to the else and executes group 3 of commands between the
else and the end.

Fig. 3.3 The structure of if-elseif-else-end conditional statement

Department of Mechanical Engineering, AITS, Rajampet. Page 27


Note: This handout is only for academic use.
Optimization lab with MATLAB software

It should be pointed out here that several elseif statements and associated groups of commands
can be added. In this way more conditions can be included. Also, the else statement is optional.
This means that in the case of several elseif statements and no else statement, if any of the
conditional statements is true the associated commands are executed; otherwise nothing is
executed.
Example:
The tank in a water tower has the geometry shown in the fig. 3.4 (the lower part is a cylinder and
the upper part is an inverted frustum of a cone). Inside the tank there is a float that indicates the
level of the water. Write a MATLAB program that determines the volume of the water in the
tank from the position (height h) of the float. The program asks the user to enter a value of h in
m, and as output displays the volume of the water in m3.

Fig. 3.4 Water Tower


For 0 ≤ h ≤ 19m the volume of the water is given by the volume of a cylinder with height h: 𝑉 =
𝜋 12.52 ℎ
For 19 < h < 33m the volume of the water is given by adding the volume of a cylinder with h =
19m, and the volume of the water in the cone:
1
𝑉 = 𝜋 12.52 . 19 + 𝜋 (ℎ − 19)(12.52 + 12.5 . 𝑟ℎ + 𝑟ℎ2 )
3

10.5
Where 𝑟ℎ = 12.5 + (ℎ − 19)
14

Matlab Progam (m-file)


h=input('Please enter the heigh of the float in meter ');
if h > 33
disp('ERROR: The height cannot be larger than 33m')
elseif h < 0
disp('ERROR: The height cannot be a negative number')

Department of Mechanical Engineering, AITS, Rajampet. Page 28


Note: This handout is only for academic use.
Optimization lab with MATLAB software

elseif h<=19
v=pi*12.5^2*h;
fprintf('The volume of the water is %5.2f cubic meter \n', v)
else
rh = 12.5+10.5*(h-19)/14;
v=pi*12.5^2*19+pi*(h-19)*(12.5^2+12.5*rh+rh^2)/3;
fprintf('The volume of the water is %7.3f cubic meter \n',v)
end
Matlab output (for various values)
Please enter the height of the float in meter 8
The volume of the water is 3926.99 cubic meter
Please enter the height of the float in meter 25.7
The volume of the water is 14114.742 cubic meter
Please enter the height of the float in meter 35
ERROR: The height cannot be larger than 33m

3.5 Loops
A loop is another method to alter the flow of a computer program. In a loop, the
execution of a command, or a group of commands, is repeated several times consecutively. Each
round of execution is called a pass. In each pass at least one variable, but usually more than one,
or even all the variables that are defined within the loop, are assigned new values. MATLAB has
two kinds of loops. In for-end loops the number of passes is specified when the loop starts. In
while-end loops the number of passes is not known ahead of time, and the looping process
continues until a specified condition is satisfied. Both kinds of loops can be terminated at any
time with the break command
For loops

Fig. 3.5 The structure of a for-end loop

Department of Mechanical Engineering, AITS, Rajampet. Page 29


Note: This handout is only for academic use.
Optimization lab with MATLAB software

 In the first pass k = f and the computer executes the commands between the for and end
commands. Then, the program goes back to the for command for the second pass. k
obtains a new value equal to k = f + s, and the commands between the for and end
commands are executed with the new value of k. The process repeats itself until the last
pass, where k = t. Then the program does not go back to the for, but continues with the
commands that follow the end command. For example, if k = 1:2:9, there are five loops,
and the corresponding values of k are 1, 3, 5, 7, and 9.
 The increment s can be negative (i.e.; k = 25:–5:10 produces four passes with k = 25, 20,
15, 10).
 If the increment value s is omitted, the value is 1 (default) (i.e.; k = 3:7 produces five
passes with k = 3, 4, 5, 6, 7).
 If f = t, the loop is executed once.
 If f > t and s > 0, or if f < t and s < 0, the loop is not executed.
 In the for command k can also be assigned a specific value (typed as a vector). Example:
for k = [7 9 –1 3 3 5]. The value of k should not be redefined within the loop. Each for
command in a program must have an end command.
A simple example of a for-end loop (in a script file) is:
for k=1:3:10
x=k^2
end
When this program is executed, the loop is executed four times. The value of k in the four
passes is k = 1, 4, 7, and 10, which means that the values that are assigned to x in the passes are
x = 1, 16, 49, and 100 respectively. Since a semicolon is not typed at the end of the second line,
the value of x is displayed in the Command Window at each pass. When the script file is
executed, the display in the Command Window is (vertically(:
x= 1 x= 16 x= 49 x = 100
Example: Print the square root of the first n integers
Matlab Progam (m-file)
n=5;
for i=1:n
fprintf('%6d %8.4f \n',i,sqrt(i));
end

Department of Mechanical Engineering, AITS, Rajampet. Page 30


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Matlab output
1 1.0000
2 1.4142
3 1.7321
4 2.0000
5 2.2361
While loops
while-end loops are used in situations when looping is needed but the number of passes is
not known in advance. In while-end loops the number of passes is not specified when the looping
process starts. Instead, the looping process continues until a stated condition is satisfied.
The structure of while-end loop is shown below:

Fig. 3.6 The structure of while-end loop


For a while-end loop to execute properly:
 The conditional expression in the while command must include at least one variable.
 The variables in the conditional expression must have assigned values when MATLAB
executes the while command for the first time.
 At least one of the variables in the conditional expression must be assigned a new value
in the commands that are between the while and the end. Otherwise, once the looping
starts it will never stop since the conditional expression will remain true.
An example of a simple while-end loop is shown in the following program. In this program a
variable x with an initial value of 1 is doubled in each pass as long as its value is equal to or
smaller than 15.

Department of Mechanical Engineering, AITS, Rajampet. Page 31


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Note: No one is free from making mistakes, a situation of indefinite looping can occur in spite
of careful programming. If this happens, the user can stop the execution of an indefinite loop by
pressing the Ctrl + C or Ctrl + Break keys.
Switch structure make it possible to skip commands or to execute specific groups of
commands in different situations. Refer to online help in MATLAB for switch structure.

3.6 Elementary Plots and Graphs

Plots are a very useful tool for presenting information. MATLAB has many commands that can
be used for creating different types of plots. These include standard plots with linear axes, plots
with logarithmic and semi-logarithmic axes, bar and stairs plots, polar plots, three-dimensional
contour surface and mesh plots, and many more. The plots can be formatted to have a desired
appearance. The line type (solid, dashed, etc.), color, and thickness can be prescribed; line
markers and grid lines can be added, as can titles and text comments.

Department of Mechanical Engineering, AITS, Rajampet. Page 32


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Fig. 3.7 Two-dimensional plot window

The plot command is used to create two-dimensional plots. The simplest form of the command is

plot(x,y)

The arguments x and yare each a vector (one-dimensional array). The two vectors must
have the same number of elements. When the plot command is executed, a figure is created in
the Figure Window. If not already open, the Figure Window opens automatically when the
command is executed. The figure has a single curve with the x values on the abscissa (horizontal
axis) and the y values on the ordinate (vertical axis)

Example:

>> x=[1 2 4 6 7.5 8 9];


>> y=[4 2 1 6 7.5 8 9];
>>plot(x,y)

Department of Mechanical Engineering, AITS, Rajampet. Page 33


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Fig. 3.8 The figure window with simple plot

The plot command has additional, optional arguments that can be used to specify the color and
style of the line and the color and type of markers, if any are desired. With these options the
command has the form

Example plot a given data: The following table contains number of machines and time taken for
processing the jobs.

No. of machines 1 2 3 4 5 6 7 8 9
Time taken for processing 30 40 43 56 41 78 89 92 95
the jobs

To plot this data, the list of years is assigned to one vector (named machine) and the
corresponding time taken for jobs is assigned to second vector (named time).

>>machine=[1:1:9];
>>jobs=[30 40 43 56 41 78 89 92 95];
>>plot(machine,jobs,'--b*','linewidth',2,'markersize',12)

Department of Mechanical Engineering, AITS, Rajampet. Page 34


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Fig 3.9 Fig. 3.10

Example: Create the script file and type the following code (fig 3.10)
x = [0:0.01:10];
y = sin(x);
g = cos(x);
plot(x,y),xlabel('x'),ylabel('Sin(x)'),title('Sin(x) Graph'),
grid on, axis equal

Example: Create the script file and type the following code
x = [0:0.01:10];
y = sin(x);
g = cos(x);
plot(x,y,'r',x,g,'b'),legend('Sin(x)','Cos(x)'),axis([0 10 -1
1])

Fig. 3.11 Output figure window

Department of Mechanical Engineering, AITS, Rajampet. Page 35


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Table 3.1: Styles, Colors and markers used in MATLAB

Department of Mechanical Engineering, AITS, Rajampet. Page 36


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Exercise 3
1. Write script file and a function file to print the square root of the even integers up to n, by
using for loop. (for both script and function file the output should be like)
2 1.4142
4 2.0000
6 2.4495
2. Write a script file to test the integer is even or odd. (use if-else)
3. Write a program which calculates the tip in the restaurant according to the amount of the
bill, if the bill is less than 10$ the tip is $1.80. If the bill is between $10 and $60 the tip is
18% of the bill, if the bill is above $60 the tip is 20% of the bill.
4. Write a function M-file that computes the following function, where x should be scalar.
sin(𝑥)/𝑥 𝑥 ≠ 0
𝑓(𝑥) = {
1 𝑥=0
5. Write a script and function file by using while loop to display all powers of two from 2
to 10.
6. Write a function file for Global stiffness matrix for a two node element
(one dimensional), where a is cross-section area, e is young’s modulus, l is length of the
element and n is number of elements.
7. Write a script and function file that gives the factorial of a positive number. Use
command name as fact (use for loop)
8. By using for loop in a function, write a program for Fibonacci series of generating n
numbers? Use the command name as fib.
9. Let us draw the graph of two polynomials; Write the code in script file? Range [-10,10]
a) 𝑓(𝑥) = 3𝑥 4 + 2𝑥 3 + 7𝑥 2 + 2𝑥 + 9 and
b) 𝑔(𝑥) = 5𝑥 3 + 2𝑥 + 2
10. Write the script for plotting the cardioid curve with the following parametric equations
𝜋
with at range of 0: ∶ 2𝜋 ; Take a =3 (can check for any value)
100
𝑥 = 𝑎(2 cos 𝑡 − cos 2𝑡) ; 𝑦 = 𝑎(2 sin 𝑡 − sin 2𝑡)

Department of Mechanical Engineering, AITS, Rajampet. Page 37


Note: This handout is only for academic use.
Optimization lab with MATLAB software

CHAPTER - IV

MATLAB for Optimization (Linear programming)


4.1 Linear Programming Solving
Find the minimum of a problem specified by
𝐴. 𝑥 ≤ 𝑏
𝑇
𝑚𝑖𝑛 𝑓 𝑥 𝑠𝑢𝑐ℎ 𝑡ℎ𝑎𝑡 {𝐴𝑒𝑞. 𝑥 = 𝑏𝑒𝑞
𝑙𝑏 ≤ 𝑥 ≤ 𝑢𝑏
f, x, b, beq, lb, and ub are vectors, and A and Aeq are matrices.
Basic Syntax for linear programming
x = linprog(f,A,b)
Solves min f'*x such that A*x ≤ b.
x = linprog(f,A,b,Aeq,beq) solves the problem above while additionally satisfying the equality
constraints Aeq*x = beq. Set A = [ ] and b = [ ] if no inequalities exist.
x = linprog(f,A,b,Aeq,beq,lb,ub) defines a set of lower and upper bounds on the design variables,
x, so that the solution is always in the range lb ≤ x ≤ ub. Set Aeq = [ ] and beq = [ ] if no
equalities exist.
Example: 1
Solve the simple Linear Programming problem with MATLAB
𝑀𝑖𝑛𝑖𝑚𝑖𝑧𝑒 𝑧 = −𝑥1 − 2𝑥2
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 − 2𝑥1 + 𝑥2 ≤ 2,
−𝑥1 + 𝑥2 ≤ 3,
𝑥1 ≤ 3,
We define
2 −2 1
1
𝑓 = − [ ] , 𝑏 = [3] , 𝐴 = [−1 1]
2
3 1 0
Matlab provides the command linprog to find the minimizer (solution point) x of a linear
programming minimum problem. Without equality constraint the syntax is
>> f= -[1;2]; b=[2;3;3];A=[-2 1;-1 1;1 0];
>> x=linprog(f,A,b)
Optimization terminated.
x=
3.0000 6.0000
For retrieve the minimal value use fmin or fopt
>> [x,fmin]=linprog(f,A,b)
Optimization terminated.
x=
3.0000 6.0000
fmin = -15.0000
Example: 2

Department of Mechanical Engineering, AITS, Rajampet. Page 38


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Solve the Linear Programming problem with MATLAB


𝑀𝑎𝑥𝑖𝑚𝑖𝑧𝑒(12 𝑥1 + 7 𝑥2 )
subject to
2 𝑥1 + 𝑥2 ≤ 10000
3𝑥1 + 2𝑥2 ≤ 16000
𝑥1 ≥ 0,
𝑥2 ≥ 0
If we define
10000 2 1
12 3 2
𝑓 = − [ ] , 𝑏 = [16000] , 𝐴 = [ ]
7 0 −1 0
0 0 −1
Matlab provides the command linprog to find the minimizer (solution point) x of a
linearprogramming minimum problem. Without equality constraint the syntax is
>> f=[-12;-7];b=[10000;16000;0;0];A=[2 1;3 2;-1 0;0 -1];
>> x=linprog(f,A,b)
Optimization terminated.
x=
1.0e+003 * 4.0000 2.0000
For retrieve the minimal value use fmin or fopt
>> [x,fmin]=linprog(f,A,b)
Optimization terminated.
x=
1.0e+003 * 4.0000 2.0000
fmin =
-6.2000e+004
Example: 3
Solve the Linear Programming problem with MATLAB
4𝑥1 + 2𝑥2 + 𝑥3 = 𝑚𝑎𝑥𝑖𝑚𝑖𝑧𝑒
subject to
2𝑥1 + 𝑥2 ≤ 1
𝑥1 + 2𝑥3 ≤ 2
𝑥1 + 𝑥2 + 𝑥3 = 1
𝑥1 ≤ 1
𝑥2 ≤ 1
𝑥3 ≤ 2
𝑥1 ≥ 0; 𝑥2 ≥ 0; 𝑥3 ≥ 0
We define

Department of Mechanical Engineering, AITS, Rajampet. Page 39


Note: This handout is only for academic use.
Optimization lab with MATLAB software

4
2 1 0 1
𝑓 = − [2] , 𝐴= [ ], 𝑏 = [ ], 𝐴𝑒𝑞 = [1 1 1], 𝑏𝑒𝑞 = [1],
1 0 2 2
1
0 1
𝑙𝑏 = [0] , 𝑢𝑏 = [1]
0 2

>> f=-[4;2;1];
>> A=[2 1 0;1 0 2];
>> b=[1;2];
>>Aeq=[1 1 1];
>>beq=[1];
>>lb=[0;0;0];
>>ub=[1;1;2];
>> x=linprog(f,A,b,Aeq,beq,lb,ub)
Optimization terminated.
x=
0.5000 0.0000 0.5000
In this case the lower boundary value is given empty set then output is
>>lb=[ ];
>> x=linprog(f,A,b,Aeq,beq,lb,ub)
Optimization terminated.
x=
0.6667 -0.3333 0.6667
In this case the Aeq and beq are given empty set then the output is
>>Aeq=[ ];
>>beq=[ ];
>> x=linprog(f,A,b,Aeq,beq,lb,ub)
Optimization terminated.
x=
0
1
1

Department of Mechanical Engineering, AITS, Rajampet. Page 40


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Exercise 4
1. Solve the linear programming problem using MATLAB
min(−𝑥1 − 2𝑥2 )
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 − 2𝑥1 + 𝑥2 ≤ 2
−𝑥1 + 𝑥2 ≤ 3
𝑥1 ≤ 3
2. Solve the linear programming problem using MATLAB
min(1.5 𝑥1 + 2.5𝑥2 )
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 𝑥1 + 3𝑥2 ≥ 3
𝑥1 + 𝑥2 ≥ 2
𝑥1 , 𝑥2 ≥ 0
3. Solve the linear programming problem using MATLAB
max(3𝑥1 + 2𝑥2 )
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 𝑥1 + 𝑥2 ≤ 4
𝑥1 − 𝑥2 ≤ 2
𝑥1 , 𝑥2 ≥ 0
4. Solve the linear programming problem using MATLAB
𝑥1 + 𝑥2 = (𝑚𝑎𝑥𝑖𝑚𝑖𝑧𝑒)
subject to 2𝑥1 + 𝑥2 ≤ 29,
𝑥1 + 2𝑥2 ≤ 25,
𝑥1 ≥ 2,
𝑥2 ≥ 5.
5. Solve the linear programming problem using MATLAB
𝑚𝑎𝑥𝑖𝑚𝑖𝑧𝑒 (143 𝑥 + 60 𝑦)
subject to
𝑥 + 𝑦 ≤ 75,
110𝑥 + 30𝑦 ≤ 4000,
120𝑥 + 210𝑦 ≤ 15000,
𝑥 ≥ 0, 𝑦 ≥ 0

Department of Mechanical Engineering, AITS, Rajampet. Page 41


Note: This handout is only for academic use.
Optimization lab with MATLAB software

6. Solve the linear programming problem using MATLAB


max(3𝑥1 + 5𝑥2 )
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 3𝑥1 + 2𝑥2 ≤ 18
𝑥1 ≤ 4
𝑥2 ≤ 6
𝑥1 , 𝑥2 ≥ 0
7. Solve the linear programming problem using MATLAB
max(2𝑥1 + 4𝑥2 + 3𝑥3 )
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 2𝑥1 + 𝑥2 − 𝑥3 ≤ 2
−2𝑥1 + 𝑥2 − 5𝑥3 ≥ −6
4𝑥1 + 𝑥2 + 𝑥3 ≤ 6
𝑥1 , 𝑥2 , 𝑥3 ≥ 0
8. Solve the linear programming problem using MATLAB
min(x1 − 3x2 + 2x3 )
Subject to 3x1 − x2 + 2x3 ≤ 7
−2x1 + 4x2 ≤ 12
−4 x1 + 3 x2 + 8x3 ≤ 10
x1 , x2 , x3 ≥ 0
9. Solve the linear programming problem using MATLAB
minimize (4x1 + 5x2 + 6x3 )
subject to 2x1 + 3x3 ≥ 6,
2x1 + 3x2 + 2x3 = 8,
5x1 − 2x2 + 5x3 ≤ 10,
x1 , x2 , x3 ≥ 0

10. Solve the linear programming problem using MATLAB


maximize (4x1 + 2x2 + 6x3 )
subject to 2x1 + 3x2 + 2x3 ≥ 6,
3x1 + 4x2 = 8,
6x1 − 4x2 + x3 ≤ 10,
x1 , x2 , x3 ≥ 0

Department of Mechanical Engineering, AITS, Rajampet. Page 42


Note: This handout is only for academic use.
Optimization lab with MATLAB software

CHAPTER - V

Optimization using MATLAB toolboxes


Optimization is the process of finding the point that minimizes a function. More specifically:

 A local minimum of a function is a point where the function value is smaller than or
equal to the value at nearby points, but possibly greater than at a distant point.
 A global minimum is a point where the function value is smaller than or equal to the
value at all other feasible points.

Generally, Optimization Toolbox solvers find a local optimum. (This local optimum can
be a global optimum.) They find the optimum in the basin of attraction of the starting point.

In contrast, Global Optimization Toolbox solvers are designed to search through more
than one basin of attraction. They search in various ways:

 GlobalSearch and MultiStart generate a number of starting points. They then use a local
solver to find the optima in the basins of attraction of the starting points.
 ga uses a set of starting points (called the population) and iteratively generates better
points from the population. As long as the initial population covers several basins, ga can
examine several basins.
 simulannealbnd performs a random search. Generally, simulannealbnd accepts a point if
it is better than the previous point. simulannealbnd occasionally accepts a worse point, in
order to reach a different basin.
 patternsearch looks at a number of neighboring points before accepting one of them. If
some neighboring points belong to different basins, patternsearch in essence looks in a
number of basins at once.

Department of Mechanical Engineering, AITS, Rajampet. Page 43


Note: This handout is only for academic use.
Optimization lab with MATLAB software

5.1 How to get the Optimization tool box in MATLAB

Go to command window and type the command optimtool and press enter button. A window
display as shown below.

Enter the Fitness Click to display description of options


function

Start process for any Results are displayed


algorithm here

5.2 Minimizing a fitness function using the Genetic Algorithm

A simple Fitness function, here we want to minimize a simple function of two variables

min 𝑓(𝑥) = 100 (𝑥12 − 𝑥2 )2 + (1 − 𝑥1 )2

Step 1: Coding the Fitness function

We create a MATLAB file named simple_fitness.m with the following code in it

function y = simple_fitness(x)
y=100*(x(1)^2-x(2))^2 + (1 - x(1))^2;
end

Department of Mechanical Engineering, AITS, Rajampet. Page 44


Note: This handout is only for academic use.
Optimization lab with MATLAB software

The Genetic Algorithm solver assumes the fitness function will take one input x where x
is a row vector with as many elements as number of variables in the problem. The fitness
function computes the value of the function and returns that scalar value in its one return
argument y.

Step 2: Minimizing using GA

To minimize our fitness function using the ga function, we need to pass in a function handle to
the fitness function as well as specifying the number of variables in the problem. The following
code has to be type in MATLAB command window.

>> fitnessfunction = @simple_fitness;


>> numberofvariables=2;
>> [x,fval]=ga(fitnessfunction,numberofvariables)
Optimization terminated: average change in the fitness value less than options.TolFun.
x=
0.9652 0.9340
fval =
0.0017

Final point value in Optimization tool box using ga-Genetic Algorithm solver
Here first we have to select the solver, mention the fitness function name and also the number of
variables. Then click the start button to check the results.

Department of Mechanical Engineering, AITS, Rajampet. Page 45


Note: This handout is only for academic use.
Optimization lab with MATLAB software

5.3 Minimization Using Simulated Annealing Algorithm

A Simple Objective Function, we want to minimize a simple function of two variables

4
𝑚𝑖𝑛 𝑓(𝑥) = (4 − 2.1 𝑥12 + 𝑥13 ) 𝑥12 + 𝑥1 𝑥2 + (−4 + 4𝑥22 )𝑥22

Step 1: Coding the objective function

We create a MATLAB file named simple_objective.m with the following code in it

function y = simple_objective(x)
y = (4 - 2.1*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)*x(2)+(-4 + 4*x(2)^2)*x(2)^2;
end

The Simulated Annealing solver assumes the objective function will take one input x
where x has as many elements as the number of variables in the problem. The objective function
computes the scalar value of the objective and returns it in its single return argument y.

Step 2: Minimizing using SIMULANNEALBND

To minimize our objective function using the SIMULANNEALBND function, we need to pass
in a function handle to the objective function as well as specifying a start point as the second
argument.

>> ObjectiveFunction=@simple_objective;
>> x0=[0.5 0.5];
>> [x,fval,exitFlag,output]=simulannealbnd(ObjectiveFunction,x0)
Optimization terminated: change in best function value less than options.TolFun.
x=
0.0901 -0.7126
fval =
-1.0316
exitFlag =
1
output =
iterations: 2439
funccount: 2458
message: [1x80 char]
rngstate: [1x1 struct]
problemtype: 'unconstrained'
temperature: [2x1 double]
totaltime: 0.6864

Department of Mechanical Engineering, AITS, Rajampet. Page 46


Note: This handout is only for academic use.
Optimization lab with MATLAB software

The first two output arguments returned by SIMULANNEALBND are x, the best point
found, and fval, the function value at the best point. A third output argument, exitFlag returns a
flag corresponding to the reason SIMULANNEALBND stopped. SIMULANNEALBND can
also return a fourth argument, output, which contains information about the performance of the
solver

Final point value in Optimization tool box using simulannealband-Simulated Annealing


Algorithm solver
Here first we have to select the solver, mention the objective function name and also the start
point of the objective function. Then click the start button to check the results.

To minimize our objective function using the SIMULANNEALBND function, we need to pass
in a function handle to the objective function as well as specifying a start point as the second
argument.

>> ObjectiveFunction=@simple_objective;
>> x0=[0.5 0.5];
>> [x,fval,exitFlag,output]=simulannealbnd(ObjectiveFunction,x0)
Optimization terminated: change in best function value less than options.TolFun.
x=

Department of Mechanical Engineering, AITS, Rajampet. Page 47


Note: This handout is only for academic use.
Optimization lab with MATLAB software

0.0901 -0.7126
fval =
-1.0316
exitFlag =
1
output =
iterations: 2439
funccount: 2458
message: [1x80 char]
rngstate: [1x1 struct]
problemtype: 'unconstrained'
temperature: [2x1 double]
totaltime: 0.6864
The first two output arguments returned by SIMULANNEALBND are x, the best point
found, and fval, the function value at the best point. A third output argument, exitFlag returns a
flag corresponding to the reason SIMULANNEALBND stopped. SIMULANNEALBND can
also return a fourth argument, output, which contains information about the performance of the
solver

Final point value in Optimization tool box using simulannealband-Simulated Annealing


Algorithm solver
Here first we have to select the solver, mention the objective function name and also the start
point of the objective function. Then click the start button to check the results.

Department of Mechanical Engineering, AITS, Rajampet. Page 48


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Exercise 5

A. Solve the problems by using quadprog function and Optimization tool box (genetic
algorithm)
1. Minimize 𝑓 = −4𝑥1 + 𝑥12 − 2𝑥1 𝑥2 + 2𝑥22
Subject to
2𝑥1 + 𝑥2 ≤ 6
𝑥1 − 4𝑥2 ≤ 0
𝑥1 ≥ 0, 𝑥2 ≥ 0
2. Minimize 𝑓(𝑋) = 3𝑥1 + 2𝑥2 + 5𝑥32 − 4𝑥1 𝑥2 − 2𝑥1 𝑥3 − 2𝑥2 𝑥3
2 2

Subject to
3𝑥1 + 5𝑥2 + 2𝑥3 ≥ 10
3𝑥1 + 5𝑥3 ≤ 15
𝑥𝑖 ≥ 0, 𝑖 = 1,2,3
2 2
3. Minimize 𝑓 = 𝑥1 + 𝑥2 − 3𝑥1 𝑥2 − 6𝑥1 + 5𝑥2
Subject to
𝑥1 + 𝑥2 ≤ 4
3𝑥1 + 6𝑥2 ≤ 20
𝑥1 ≥ 0, 𝑥2 ≥ 0
4. Minimize 𝑓 = 𝑥1 + 𝑥1 𝑥2 + 2𝑥2 + 2𝑥32 + 2𝑥2 𝑥3 + 4𝑥1 + 6𝑥2 + 12𝑥3
2 2

Subject to
𝑥1 + 𝑥2 + 𝑥3 ≥ 6
−𝑥1 − 𝑥2 + 2𝑥3 ≥ 2
𝑥1 , 𝑥2 , 𝑥3 ≥ 0

B. Solve the problems by using Optimization toolbox (Simulated annealing)


5. Minimize the following function
𝑓(𝑥1 , 𝑥2 ) = 𝑥12 − 2𝑥1 𝑥2 + 6𝑥1 + 𝑥22 − 6𝑥2
6. Minimize the following function
𝑚𝑖𝑛𝑖𝑚𝑧𝑒 𝑓 = 𝑥12 + 𝑥1 𝑥2 + 𝑥22 + 3𝑥1 + 5𝑥2
C. Solve the problem by using Optimization toolbox (Linear programming)

7. Maximize the following function


𝑚𝑎𝑥𝑖𝑚𝑖𝑧𝑒 (4𝑥1 + 2𝑥2 + 6𝑥3 )
𝑠𝑢𝑏𝑗𝑒𝑐𝑡 𝑡𝑜 2𝑥1 + 3𝑥2 + 2𝑥3 ≥ 6,
3𝑥1 + 4𝑥2 = 8,
6𝑥1 − 4𝑥2 + 𝑥3 ≤ 10,
𝑥1 , 𝑥2 , 𝑥3 ≥ 0

Department of Mechanical Engineering, AITS, Rajampet. Page 49


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Chapter VI- Fuzzy Logic

A fuzzy logic system (FLS) can be defined as the nonlinear mapping of an input data set to a
scalar output data. A FLS consists of four main parts: fuzzifier, rules, inference engine, and
defuzzifier.

Fig.1 Fuzzy logic systems

FIS Editor:
Input
deceleration Output

Mamdami –
Double click
Name of the
to give input
Fuzzy type

Fig.2 Fuzzy editor

Firstly, a crisp set of input data are gathered and converted to a fuzzy set using fuzzy
linguistic variables, fuzzy linguistic terms and membership functions. This step is known as

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

fuzzification. Afterwards, an inference is made based on a set of rules. Lastly, the resulting fuzzy
output is mapped to a crisp output using the membership functions, in the defuzzification step.

Membership Function Editor

Fig.3 Membership function editor

Rule Editor

Fig.4 Rule editor

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

1. Given a number between 0 and 10 that represents the quality of service at a restaurant
(where 10 is excellent), and another number between 0 and 10 that represents the quality
of the food at that restaurant (again 10 is excellent), what should the tip be?
Assume that an average tip is15%, a generous tip is 25%, and a cheap tip is 5%.

Select input1 and change name to service simultaneously for input2 and output1 also.

Fig.5 Fuzzy inference system editor

Poor:0-5 ; Good:2.5–7.5; Excellent:5-10

Fig. 6 Triangular membership function Fig. 7 Gaussian membership function

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Cheap:0-15 ; Average:7.5–22.5; Generous:15-30

Fig.8 Membership function editor

Fuzzy rules

Service Food (Rancid) Food (Delicious)


Poor Cheap Average
Good Cheap Average
Excellent Generous Generous

1. If service is poor and the food is rancid then tip is cheap.


2. If service is good and the food is rancid then tip is cheap.
3. If service is poor and the food is delicious then tip is Average.
4. If service is good and the food is delicious then tip is Average.
5. If service is excellent then tip is generous.

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Fig. 9 Rule Editor Fig. 10 Rule viewer

Fig. 11 Surface Viewer

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Solved problems

1. e  163
Sol: exp(pi*sqrt(163))
ans = 2.6254e+017
2. Area = πr2 with r  1/ 3 1
Sol: r=pi^(1/3)-1;
area=pi*r^2
ans area = 0.6781
 8 
3. The moment of inertia of a sector of a circle is I     r 4 , where r is the radius of the
 8 9 
circle. Determine I when r = 2.5cm.
Sol: r=2.5;
i=(pi/8- 8/(9*pi))*r^4
ans: i = 4.2874

 
4. sin 2  cos 2
6 6
Sol: a=sind(pi/6)^2+cosd(pi)^2
a = 0.9971

x2
5. Evaluate the function y  for values of x from one to two in steps of 0.1
x 3 1
Sol:
x=1:.1:2;
y=x.^2./(x.^3+1)
y =
0.5000 0.5191 0.5279 0.5286 0.5235 0.5143
0.5024 0.4888 0.4742 0.4593 0.4444

 x cos x 
6. Evaluate the function y( x)  sin  2 , for values of x from one to three in steps of 0.2
 x  3 x 1 
Sol:
x=1:.2:3;
y=x.*cos(x)./(x.^2+3*x+1)
y =
0.1081 0.0720 0.0332 -0.0056 -0.0424 -0.0757
-0.1041 -0.1268 -0.1432 -0.1530 -0.1563

7. Find the solution of the following set of linear algebraic equations


5x = 3y – 2z + 10
8y + 4z = 3x + 20
2x + 4y - 9z = 9

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

Sol:
A=[5 -3 2;-3 8 4;2 4 -9];
B=[10 20 9]';
C=A\B
C =
3.4442
3.1982
1.1868

8. Plot a parametric space curve, x(t )  t , y(t )  t 2 , z(t )  t 3 using plot3


Sol:
t=linspace(0,5,50);
x=t;
y=t.^2;
z=t.^3;
plot3(x,y,z)

9. Suppose that the squares of all positive odd integers were to be added up until this sum first
equals or exceeds 100. How many terms would be added? What is the final sum?
Sol:
clc
clear all
sum=0;
nterm=0; %% Count the number of terms
i=1;
while sum<=100
oldsum=sum;
sum=sum+i*i;
i=i+2;
nterm=nterm+1;
%fprintf('%6d \n',nterm);
end
fprintf('Number of terms is:%2d \n',nterm);
fprintf('The final sum is :%2d \n',oldsum);

10. Let ‘R’ be the radius of a circle. Prepare a script and function file to execute Area and
Perimeter of a circle?

Sol:
clc
clear all
pi = 3.17;
r = input('Enter the radius of a circe:');
area = pi * (r^2)
perimenter = 2*pi*r

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.
Optimization lab with MATLAB software

NOTES

Department of Mechanical Engineering, AITS, Rajampet.


Note: This handout is only for academic use.

You might also like