Matlab Manual 2020 21 Mechanical
Matlab Manual 2020 21 Mechanical
OPTIMIZATION LAB
WITH MATLAB
SOFTWARE
Department of Mechanical Engineering
Chapter – I
Title Window
Menu bar
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.
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.
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
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.
Example for Elementary Functions: while using the elementary functions the function syntax
is function (x) ,where x indicates the value
MAT LAB environment behaves like a super-complex calculator. You can enter commands at
the >> command prompt.
Adding Comments:
The percent symbol (%) is used for indicating a comment line. For example
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 ?
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
Chapter - II
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.
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.
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.
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.
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
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.
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.
Order of Precedence
Below table shows order of precedence in MATLAB
If two or more operations have the same precedence, the expression is executed in order
from left to right.
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?
CHAPTER - III
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)
skips the group of commands between the if and the end, and continues with the commands that
follow the end.
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
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
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.
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.
10.5
Where 𝑟ℎ = 12.5 + (ℎ − 19)
14
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
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
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:
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.
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.
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:
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)
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])
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𝑡)
CHAPTER - IV
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
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
CHAPTER - V
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.
Go to command window and type the command optimtool and press enter button. A window
display as shown below.
A simple Fitness function, here we want to minimize a simple function of two variables
function y = simple_fitness(x)
y=100*(x(1)^2-x(2))^2 + (1 - x(1))^2;
end
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.
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.
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.
4
𝑚𝑖𝑛 𝑓(𝑥) = (4 − 2.1 𝑥12 + 𝑥13 ) 𝑥12 + 𝑥1 𝑥2 + (−4 + 4𝑥22 )𝑥22
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.
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
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
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
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
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
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.
FIS Editor:
Input
deceleration Output
Mamdami –
Double click
Name of the
to give input
Fuzzy type
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
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.
Rule Editor
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.
Fuzzy rules
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
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
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
NOTES