M</em>ATLAB<em><sup>®</sup></em><em> as a Computation Tool - HELPFUL PRELIMINARIES - Optimization in Practice with MATLAB for Engineering Students and Professionals (2015)

Optimization in Practice with MATLAB for Engineering Students and Professionals (2015)

PART 1


HELPFUL PRELIMINARIES

Part I provides prerequisite information for using optimization in practice. Specifically, we need to use software and we need to have some basic knowledge of mathematics. This book uses MATLAB as a computational tool. If you are new to MATLAB or do not know it yet, Chapter 1 will provide you with the preparatory information to get started. If your mathematics knowledge is a bit rusty, Chapter 2 will provide you with the preparatory knowledge for optimization application.

Specifically, the topics presented, with the chapter numbers, are given below:

1.MATLAB® as a Computation Tool


2.Mathematical Preliminaries

1


MATLAB® as a Computational Tool

1.1 Overview

Optimization can be viewed as a process that searches methodically for better answers, better solutions, or better designs that a human being may not be able to find through experience, intuition, or courageous trial-and-error. Optimization can be defined as the art of making things better. Interestingly, optimization very often does not simply allow us to do something better, but it may also make it possible to do something that we did not otherwise know how to do. To take full advantage of the power of optimization in practice, there is no choice but to use a computer.

The study of optimization typically takes a theoretical and/or computational approach. The theoretical approach is highly useful when the objective is to develop new optimization methods or to assess how the current methods work [1]. Additionally, the study of optimization often focuses on the understanding of various search algorithms for optimization. A book by Reklaitis and co-authors [2] is an example of methods-based optimization presentation. While these books play an important role in the general study of optimization, we pursue a different approach. The objective of this book takes on a practical perspective. The current interest is in the immediate ability to apply optimization in practice. In order to reach this objective, and to have the ability to apply optimization to real world problems, we use the approach that is almost always required in the application of optimization. We use the power of the computer, in conjunction with the study of different important practical aspects of optimization.

In order readily apply optimization in practice, the focus will be on the computational application of what we will learn, as we learn it. To do so, we use a computational modeling and coding tool that is powerful, easy to use, and one that is widely applied in engineering and other fields. MATLAB is an excellent tool choice and will be used in this book. MATLAB has arguably become the most popular tool for computational modeling worldwide. Using MATLAB will enable you to optimize both simple and complex systems or designs with effectiveness and efficiency.

MATLAB is a registered trademark of The MathWorks, Inc.

This chapter provides a brief introduction to MATLAB, which is primarily for those who have little or no experience with MATLAB. Previous users of MATLAB may find this introduction to be a useful review and a way to learn about the MATLAB optimization capabilities. This chapter has six sections. Section 1.2 defines MATLAB. Section 1.3 provides a basic introduction of MATLAB, while Sec. 1.4 goes beyond the basics. Section 1.5 focuses on the MATLAB plotting capabilities. In Sec. 1.6, the MATLAB nonlinear and linear optimization capabilities are introduced. For historical reasons, the terminology “linear programming” and “nonlinear programming” is often used synonymously with “linear optimization” and “nonlinear optimization,” respectively. In Sec. 1.7, a list of useful functions is presented.

1.2 MATLAB Preliminaries—Before Starting

This section provides useful information about MATLAB as a software tool. It includes the following components:

1.What is MATLAB?

2.Why MATLAB?

3.MATLAB Toolboxes

4.How to Use MATLAB in This Book?

5.Acquiring MATLAB

6.MATLAB Documentation

7.Other Software for Optimization

1.2.1 What Is MATLAB?

MATLAB is a very popular high level language for computation. It is used extensively both in industry and in universities worldwide. It is much easier to use than other popular programming languages such as Fortran or C. It takes a very short time to start becoming productive with MATLAB. Mathematical expressions are evaluated much the same way as they would be written in text form. MATLAB is used for a wide variety of activities, including computation, algorithm development, modeling, simulation, prototyping, data analysis, visualization, engineering graphics, and graphical user interface building (Ref. [3]).

In this book, the use of MATLAB is limited to the context of the application of optimization. In doing so, we will be able to optimize practically any system. This is because the MATLAB environment is very powerful. We will be able to optimize any system that is modeled in the MATLAB computational environment using this newly acquired optimization knowledge.

Over the years, various parties have developed MATLAB tools that are applicable to specific fields. These tools essentially constitute a set of functions that work together to perform powerful tasks in specific technical areas, such as control, dynamics, financial analysis, and signal processing. Some are available through private parties, while others are available through the MATLAB developer (The MathWorks, Inc.) [4]. Information concerning MATLAB can be obtained from its developer or at the website www.mathworks.com.

MATLAB is organized as a collection of several independent components that work together harmoniously. The central component is the basic MATLAB software, which can be used for most general computation and algorithm development. When the needs become more advanced and specific, we acquire MATLAB Toolboxes. These toolboxes are a collection of MATLAB function codes that perform tasks in given technical areas. To perform advanced optimization, the basic MATLAB software is needed, together with the “Optimization” Toolbox.

MATLAB can be acquired in the form of professional and educational versions [4]. The latter has some reduced capabilities, but should be able to perform most required tasks for moderately sized problems.

1.2.2 Why MATLAB?

It is important to keep in mind that MATLAB is in no way required to perform computational optimization. Several other codes could be used to perform all of the tasks for which MATLAB can be used. However, for the purpose of this book, MATLAB is an excellent choice. It is also a recommended software for future activities after completing the study of optimization using this book. Related information is also discussed in the Preface.

1.2.3 MATLAB Toolboxes

MATLAB Toolboxes provide useful functions for research and development in technical fields. Specific tasks can be performed using these toolboxes to satisfy users’ requirements through user-friendly commands or visual interfaces. These toolboxes are convenient to use, as well as powerful. They provide functions that can be called by the MATLAB code written by users. The toolboxes support various functionalities for a broad range of applications. They are available for applications in (1) parallel computing, (2) mathematics, statistics, and optimization, (3) control system design and analysis, (4) signal processing and communications, (5) image processing and computer vision, (6) test and measurement, (7) computational finance, (8) computational biology, and (9) database connectivity and reporting. A complete list of MATLAB Toolboxes is available at the MathWorks website. The list includes the following toolboxes.

1.Parallel Computing

•Parallel Computing Toolbox

2.Math, Statistics, and Optimization

•Symbolic Math Toolbox

•Partial Differential Equation Toolbox

•Statistics Toolbox

•Curve Fitting Toolbox

•Optimization Toolbox

•Global Optimization Toolbox

•Neural Network Toolbox

•Model-Based Calibration Toolbox

3.Control System Design and Analysis

•Control System Toolbox

•System Identification Toolbox

•Fuzzy Logic Toolbox

•Robust Control Toolbox

•Model Predictive Control Toolbox

•Aerospace Toolbox

4.Signal Processing and Communications

•Signal Processing Toolbox

•DSP System Toolbox

•Communications System Toolbox

•Wavelet Toolbox

•Fixed-Point Toolbox

•RF Toolbox

•Phased Array System Toolbox

5.Image Processing and Computer Vision

•Image Processing Toolbox

•Computer Vision System Toolbox

•Image Acquisition Toolbox

•Mapping Toolbox

6.Test and Measurement

•Data Acquisition Toolbox

•Instrument Control Toolbox

•Image Acquisition Toolbox

•OPC Toolbox

•Vehicle Network Toolbox

7.Computational Finance

•Financial Toolbox

•Econometrics Toolbox

•Datafeed Toolbox

•Database Toolbox

•Financial Instruments Toolbox

8.Computational Biology

•Bioinformatics Toolbox

9.Database Connectivity and Reporting

•Database Toolbox

MATLAB users can develop unique toolboxes for specific purposes. Many of these user-developed toolboxes are available online for download and use.

This book focuses on optimization using MATLAB Toolboxes. The optimization toolbox and the Global Optimization Toolbox are used for the study of optimization.

To access the MATLAB Toolboxes, you can click the APPS tab (Fig. 1.1) at the top menu of the MATLAB Desktop. The toolboxes have graphical user interfaces. A more advanced way to use the MATLAB Toolboxes is to call their functions using MATLAB codes. In this book, different MATLAB optimization functions are used to solve different types of problems.

PIC

Figure 1.1. MATLAB Desktop

1.2.4 How to Use MATLAB in this Book

This book provides a brief introduction to MATLAB to help with the initial use of MATLAB. Also provided is information regarding how to perform optimization using MATLAB. When it is deemed helpful and practical, the actual MATLAB code will be provided. By examining these preliminary coding examples, it will become clear how to write other more complicated code. Some code will be provided in the text, while others will be provided in the media device that accompanies this book. It is assumed that the PC Windows version of MATLAB 2013 is being used. The distinctions between the different platform versions of MATLAB are minor. The basic code is almost always identical across platforms, except for some tasks, such as file manipulations.

1.2.5 Acquiring MATLAB

MATLAB is widely available in most engineering firms and universities, as well as many financial institutions. It can be purchased from the MATLAB developer [4]. This book makes use of the basic MATLAB software and of the optimization toolbox software. Both are required to perform the computational portion of this book. It should also be noted that several other software options can be used to do this computational optimization work.

1.2.6 MATLAB Documentation

Several forms of documentation are available for the MATLAB user. An abundance of information is available on the web and on the developer’s website. Several books that document the different components of MATLAB are sold by The MathWorks. Many of these books can also be downloaded from The MathWorks’ website [4].

MATLAB documentation books can be downloaded from the website [4]. The powerful capabilities of the MATLAB graphics are presented in the book entitled MATLAB Graphics [5]. A book entitled MATLAB Primer provides a handy documentation of MATLAB [6] and, for the novice, a good basic introduction of MATLAB is given in the book entitled Basics of MATLAB and Beyond (Ref. [7]) or Getting Starter with MATLAB: a Quick Introduction for Scientists and Engineers (Ref. [8]). We note that the information provided here is fluid and dynamic. A visit to the developer’s website [4] and a web search will provide the latest information.

1.2.7 Other Software for Optimization

MATLAB is not unique in its ability to perform computational optimization. It is chosen here because it is a highly effective software that is user-friendly and widely used. The skills that will be developed are useful in numerous other fields.

By using the MATLAB Toolboxes, it is possible to perform optimization in a number of different technical areas. This is because these toolboxes provide the means to model the performance behavior of the pertinent systems.

In certain situations, it is more appropriate to use other software, either independently or in conjunction with MATLAB. When used in conjunction with MATLAB, the external interface capability of MATLAB is used. Pertinent documentation is available from the MATLAB help menu or from The MathWorks’ website.

There is a plethora of optimization software available to perform optimization independently. A book entitled Optimization Software Guide [9] catalogs a large number of these software tools. Notable optimization software products in the area of structural optimization are GENESIS [10], MSC/Nastran [11], and Altair [12]. Genesis was explicitly developed for the purpose of structural optimization and is considered a powerful tool.

1.3 Basics of MATLAB—Getting Started

This section provides a brief description of how to get around MATLAB and of how to use MATLAB at an introductory level. Specifically, the following topics are presented:

1.Starting and Quitting Matlab

2.Matlab Desktop: Basic MATLAB Graphical User Interface

3.Matrices and Variables: Matrices and Variables Operations

4.Expressions: Evaluations of Mathematical Expressions

5.Control Flow Statements: Using the for loop, the while loop, the if statement, and others

6.Input and Output, Directories, and Files: Input and Output of Data and Editing Commands, Directories, and Files

7.Script File: File that has MATLAB Commands

8.Function File: MATLAB File that Performs Independent Tasks

9.Plotting: Elementary Plotting Capabilities of MATLAB

1.3.1 Starting and Quitting MATLAB

To start MATLAB in Microsoft Windows, double-click on the MATLAB icon on the Windows desktop. MATLAB can also be started by selecting MATLAB from the Start menu. On a UNIX platform, type matlab at the operating system prompt. Once MATLAB is launched, a MATLAB Desktop appears on the screen.

To quit MATLAB, click on the top right close window button (Fig. 1.1). Alternatively, select Exit from the File menu in the desktop, or type exit or quit in the Command Window.

1.3.2 MATLAB Desktop: Its Graphical User Interface

The MATLAB Desktop (Fig. 1.1) appears when MATLAB is started. It provides a Graphical User Interface (GUI) that facilitates various MATLAB functions, such as managing files, variables, and applications.

The first time MATLAB starts, the desktop appears as shown in Fig. 1.1, although the desktop may have been customized to contain fewer components. Customize the desktop by opening, closing, moving, docking, and resizing the tools in it. Use Preferences from the File menu to specify features of the desktop. The MATLAB desktop environment provides useful tools that can be used for various purposes.

Command Window

The Command Window (Fig. 1.2) is used to enter variables, evaluate MATLAB commands, and run M-files or functions. M-files are the programs written to run MATLAB functions.

Figure 1.2. MATLAB Command Window

Command History

The Command History window (Fig. 1.3) is used to view previously used functions, copy, and execute selected lines from those functions. The lines entered in the Command Window at the command prompt are logged into Command History.

Figure 1.3. MATLAB Command History

Current Directory Browser

The Current Directory browser (Fig. 1.4) can be used to view, open, and make changes to MATLAB related directories and files. You can also use the commands dir, cd, and delete at the command prompt to view, change, and delete directories, respectively. MATLAB uses the current directory and the search path as a reference point to run and save files.

Figure 1.4. MATLAB Current Directory

Any file you wish to run must be in the current directory or on the search path. A quick way to change the current directory is to use the Current Directory menu in the Desktop shown in Fig. 1.1.

Search Path: MATLAB uses a search path to find and execute the M files/functions you call. It also uses the search path to find other necessary MATLAB files, which are organized in the directories in the file system. By default, the files supplied with MATLAB and Mathworks Toolboxes are included in the search path. To see or modify the current search path, select Set Path from the File menu in the Desktop and use the Set Path dialog box. Use the pathcommand at the command prompt to view the current search path, addpath to add directories to the path, and rmpath to remove directories from the path.

Workspace Browser

The Workspace Browser (Fig. 1.5) is used to view the workspace and information about each variable. The MATLAB workspace consists of stored variables that are built up during a MATLAB session by running functions, M-files, and loading saved workspaces. At the command prompt, use the commands who and whos to view the workspace. To delete variables from the workspace, select the variable and select Delete from the Edit menu. Use the clear command at the command prompt. The workspace is deleted after the end of the MATLAB session. To save the workspace to a file, select Save Workspace As from the File menu, or use the save command. The workspace will be saved to a binary file, called a MAT-file, with a .mat extension. To read from a MAT-file, select Import Data from the File menu or use the load command.

Figure 1.5. MATLAB Workspace Browser

Variable Editor

Double-clicking on a variable in the Workspace Browser will open the Variable Editor (Fig. 1.6). The Variable Editor can be used to view and edit a visual representation of one or two dimensional numeric arrays, strings, and arrays of strings in the workspace.

Figure 1.6. MATLAB Variable Editor

Editor/Debugger

The Editor/debugger (Fig. 1.7) provides a GUI to create and debug M-files. To create or edit an M-file, go to File and select New, or File and select Open, or use the edit function at the command prompt.

Figure 1.7. MATLAB Editor or Debugger

Any text editor can be used to create M- files. To specify a particular text editor as the default, use Preferences from the File menu. The MATLAB Editor can be used for debugging and using such debugging functions as dbstop, which sets a breakpoint.

Help Browser

The Help browser (Fig. 1.8) is used to search and view documentation for all MATLAB products. It is a web browser integrated into the MATLAB Desktop and displays HTML documents.

Figure 1.8. MATLAB Help Browser

There are several ways to open the Help browser: (i) Click the Help button in the MATLAB Desktop (shown in Fig. 1.1), (ii) Type helpbrowser at the command prompt, or (iii) Launch help from the Start button. The Help Browser consists of two panes: the Help Navigator pane, which is used to find information and type search keywords, and the Display pane, where the information can be viewed.

More detailed information on the MATLAB Desktop and the desktop tools can be found in Refs. [4, 6], or by simply exploring it in the Help section of MATLAB.

1.3.3 Matrices and Variables Operations

This subsection begins with comments on basic expressions and long lines, which will be followed by matrices and variables operations.

Basic Expressions

The most direct way to perform calculations using MATLAB is to simply type the commands, or basic expressions, on the command prompt. For example, observe the following MATLAB commands, which were typed on the Command Window:

>> a = 1 + 2
a =
3
>> b = 4
b =
4
>> c = sqrt(a^2 + b^2)
c =
5
>> x = a + b;
>> y = 2*x
y =
14

A few basic observations can be made. After typing a=1+2, MATLAB writes the result. After typing b=4, MATLAB again writes the result. After writing the expression for c, the result is again written on the screen. In the case of the variable x, the result is not written on the screen. This is because a semicolon is typed at the end of the expression. The value of the variable x is now available in the MATLAB workspace for further computation. The value of x is available and is used to evaluate y.

Long Lines

Very long commands or expressions can be typed on several lines. To do this, begin by writing the expression on one line, then type three periods followed by Enter, and continue to type the expression on the following line. Below is an example.

>> a_long_variable = 2
a_long_variable =
2
>> another_long_variable = 3
another_long_variable =
3
>> x = a_long_variable + a_long_variable^2 ...
+ another_long_variable
x =
9

Typing Matrices

Recall that a matrix is a multidimensional variable. A 3 by 4 matrix has 3 rows and 4 columns. Define a 3 by 4 matrix M by typing in the Command Window:

>> M = [ 1 2 3 4; 5 6 7 8; 9 10 11 12]
M =
1 2 3 4
5 6 7 8
9 10 11 12

Note that entries within a row can be separated by a space (or a comma), and that a semicolon ends a row. Expressions that include matrices can be formed, such as:

>> v=[11 ; 22 ; 33]
v =
11
22
33
>> mv = [M v]
mv =
1 2 3 4 11
5 6 7 8 22
9 10 11 12 33

where we concatenate two matrices in a row (with compatible dimensions - same number of rows). Similarly, two matrices with an equal number of columns can be vertically concatenated as

>> h = [11 22 33 44]
h =
11 22 33 44

>> mh = [M ; h]
mh =
1 2 3 4
5 6 7 8
9 10 11 12
11 22 33 44

Matrices Generators

MATLAB makes it convenient to generate certain commonly used matrices. Note the following statements:

>> ones(3)
ans =
1 1 1
1 1 1
1 1 1
>> ones(1,3)
ans =
1 1 1
>> zeros(2)
ans =
0 0
0 0
>> zeros(1,3)
ans =
0 0 0
>> A = eye(3)
A =
1 0 0
0 1 0
0 0 1

Observe that the command ones(3) produces a 3 by 3 matrix of ones. Note that the command ones(3,3) will produce the same matrix. Similar comments apply to the command zeros(2). The command eye(n) will generate an identity matrix of dimension n by n.

Recall that if more information is needed, typing the commands help zero at the MATLAB prompt will provide more information about the command.

Subscripting

For the following matrix

>> A = [1 3 5; 4 6 8]
A =
1 3 5
4 6 8
>>

the following commands produce insightful results.

>> A(1,2)
ans =
3
>> A(2,end)
ans =
8

Note the use of the word end above as a subscript.

Matrix Arithmetic

Vector and matrix operations can be written in the usual way. For example, define the vector

>> v=[1;1;1]
v =
1
1
1

Using the matrix A, just defined, we can evaluate

>> A*v
ans =
9
18

Recall that the dimensions of the matrices must be compatible for the matrix multiplication to take place (see Chapter 2).

Colon Operator

Powerful matrix manipulations can be performed by using the colon (:) operator. The most direct way to use the colon operator is to type

>> a = 2:8
a =
2 3 4 5 6 7 8

where a list of numbers is generated from the lowest to the highest given numbers. Also write

>> 1:2:9
ans =
1 3 5 7 9

where the middle number is used as an increment, 2. The increment can also be negative as in

>> 50:-5:30
ans =
50 45 40 35 30

The other common use of the colon operator is to refer to a portion of a matrix. If we define the matrix

>> P=[1 2 3 4 ; 5 6 7 8]
P =
1 2 3 4
5 6 7 8

then we can retrieve the second through fourth columns of the second row using the command

>> pp = P(2, 2:4)
pp =
6 7 8

Transpose

The transpose of a matrix can be obtained as follows

>> a=[1 2 3;4 5 6]
a =
1 2 3
4 5 6
>> b = a’
b =
1 4
2 5
3 6

where b is the transpose of a, which is evaluated by a’.

The Command linspace

The linspace command is a quick way to generate a row vector of 100 linearly spaced points between two given numbers. The syntax is

linspace(100,200)

The above command generates 100 linearly spaced points between 100 and 200.

1.3.4 More MATLAB Expressions

Below are some more examples of MATLAB expressions. More information regarding these functions can be obtained by typing help followed by the function name.

>> x = 2
x =
2
>> y = exp(x) + log(x)
y =
8.0822
>> z = (-sin(y)) + abs(-x)
z =
1.0259
>> complex_number = 4 + 3i
complex_number =
4.0000 + 3.0000i
>> magnitude = abs(complex_number)
magnitude =
5

The log function evaluates the natural logarithm of a number, while the abs function evaluates the magnitude of a real or complex number.

1.4 Beyond the Basics of MATLAB

This section provides important information about MATLAB that you will need to know that is beyond the basics that we are covered so far. It will all become much easier as you get more practice. The following topics are presented:

1.Input and Output, Directories, and Files

2.Flow Control, Relational, and Logical Operators

3.M-files

4.Global and Local Variables

5.MATLAB Help

1.4.1 Input and Output, Directories and Files

The MATLAB environment can be easily manipulated to make file handling convenient. Some useful features are discussed below.

Current Directory

The current directory is generally displayed in a text box toward the top of the MATLAB screen. Alternatively, type pwd at the command prompt to display the current directory.

Setting the Path

The path to directories that are often used can be set. The files in these directories can then be directly accessed from any other directory. The path can be set from the File >> Set Path menu.

Saving and Loading Variables

Any variable in the workspace can be saved to the hard disk using the save command.

save FILENAME x y

The above command saves the workspace variables x and y to a file named FILENAME.mat in the current directory. Note that there is no comma in the above syntax. To retrieve these variables, type the command

load FILENAME x y

1.4.2 Flow Control, Relational and Logical Operators

The MATLAB flow control statements operate similarly to those in most programming languages.

The for Loop

The for loop executes a set of statements for a specified number of times.

>> for i = 1:5
x(i)=1;
end

The above for loop generates an array x of five elements, each equal to 1.

>> x
x =
1 1 1 1 1

MATLAB also provides nesting of for loops.

The while Loop

The general form of the while loop is

while EXPRESSION
STATEMENTS
end

The STATEMENTS will be executed as long as the EXPRESSION is true. For example, if the expression is A<B, then the statements will be executed while this condition holds true, and will stop executing as soon as A >=B.

The for and while loops can be terminated using the break command. The continue command passes control to the next iteration of the loop.

The if Statement

The if statement allows execution of statements provided certain conditions hold. The general form of the if statement is:

if EXPRESSION
STATEMENTS
else
STATEMENTS
end

The statements in the if part will be executed only if the EXPRESSION is true. Otherwise, the statements in the else part will be executed. The else portion is optional.

The switch-case Statements

Switch provides a way to switch between several cases based on an expression. For example, if a variable x in the workspace has a value of 2, then the following statements

>> switch x
case 1
disp(’x is equal to 1’)
case 2
disp(’x is equal to 2’)
end

will yield

x is equal to 2.

Logical and Relational Operators

MATLAB provides a number of different logical and relational operators. These operators can be used in conjunction with variables to create expressions for use in if statements, while loops, and other flow control statements. A complete list of operators can be obtained by typing help ops at the command prompt. Some commonly used relational operators are EQUAL (==), GREATER THAN (>), LESS THAN (<), and NOT EQUAL (~=). Some commonly used logical operators are: AND (&), OR (|), and NOT (~).

1.4.3 M-files

MATLAB provides the powerful M-file feature. Using this feature, a sequence of MATLAB commands can be saved as an .m file, and can be executed as a batch process by simply typing the name of the M-file.

Script M-files

Script files are a series of MATLAB commands stored in a .m file. They do not necessarily take any input or yield any output. The variables generated during the execution are stored in the MATLAB workspace. A sample filemyMfile.m is shown below.

% This is my first .m file
var = 5; new_var = var^2;
if new_var > 5
disp(‘My first output’);
end

This file can be generated using any external text editor, such as Notepad, or can be created using the MATLAB editor and debugger. The file is saved as myMfile.m in the current directory. Typing the name of the file at the command prompt will execute the commands in the file sequentially.

>> myMFile
My first output

Note that the file name is not allowed to have spaces, -, +, , *, ^ , or any other mathematical symbols. Alternatively, right-clicking on its filename in the Directory Browser and clicking on Run will also execute the file.

Function M-files

Function M-files are similar to the script M-files in that they consist of a sequence of MATLAB commands. The difference between the two is that function M-files can receive one or more variables as inputs, and can return one or more variables as outputs. The input and output variables are available for use outside of the M-file function, but the variables or parameters used inside the function are not available outside the function. All variables or parameters that are used inside a script M-file are available in the environment that calls that script M-file. The input and output variables are called arguments. Creating or modifying variables within a function M-file does not affect the workspace, unless these variables are also output variables. To use an existing function, first define the numerical values of the input arguments that will be used, then define the list of output arguments in the function call.

Here is a representative function file called cuberoot.m, which has a single variable as an input argument, and returns its cubic root.

function output_var = cuberoot(input_var)
output_var = input_var^(1/3);

The first line is the syntax definition. The name of the output variable is output_var, input_var is the name of the input variable, and cuberoot is the name of the M-file. This file should be saved as cuberoot.m in the currentdirectory.

The function cuberoot can be directly called from the command prompt. For example, to calculate the cube root of the number 5, type cuberoot(5) at the command prompt, which yields

ans =
1.7100

One can also assign the M-file function output to a workspace variable, say x, by typing x = cuberoot(5). The function M-file can be called from within a script M-file.

Subfunctions

Subfunctions can be declared following the definition of the main function in the same M-file. Subfunctions are visible to the main function and other subfunctions in the same M-file, but are not visible outside the M-file in which they are declared.

1.4.4 Global and Local Variables

All the variables created within a function M-file are local to that function, and cannot be accessed from outside the function. Similarly, workspace variables are local to the workspace, and are not available to any function. To make a workspace variable, x, globally available, use the global command as follows.

global x

The above command should be used at the beginning of every script M-file and function M-file where the global variable needs to be accessed.

1.4.5 MATLAB Help

MATLAB help can be obtained from various sources. A good way to get started is to read this introductory chapter. This introduction can be followed by reading the book MATLAB Primer [6]. Comprehensive information about MATLAB can be obtained from the many documentation books (i.e., [5]). The Mathworks’ website [4] has a large amount of information that will address almost any issue. In situations where there is no access to the web, it is possible that all the needed information is already available on the computer where MATLAB is installed. Clicking on the Help menu will indicate the extent of the help information already installed.

A direct way to get help is to type at the MATLAB prompt

•helpdesk, which opens a MATLAB help GUI,

•helpwin, which opens a hypertext help browser,

•demo, which starts the MATLAB demonstration,

•help, which prints on the screen the various help topics available,

•help followed by a help topic or any function name, which provides help on the requested topic or function, or

•lookfor followed by a topic keyword, which gives the names of all the MATLAB functions that have that keyword on the first help line (that keyword does not have to be the name of a function, unlike for the help command).

As always, perhaps the most interesting way to get help is to ask, or work with a friend who might have more experience with MATLAB.

1.5 Plotting Using MATLAB

A picture is worth of thousand words. This is very true in optimization as well. Optimization methods are understood more clearly when presented in graphical form. At every stage of working life, presenting work using graphs and charts is a critical activity. In this endeavor, MATLAB can be used with its extensive set of functions to help develop the required graphs and charts (Ref. [13]). Following are pertinent important information:

1.Basic Plots

2.Special Plots: Contour, Scatter, fplot

3.3-D Mesh and Surface Plots

4.Using the Plot Editing Mode

1.5.1 Basic Plots

First, consider the simple commands that generate two dimensional (2D) plots.

Use of Plot Command

Plot is one of the simplest graphics commands available in MATLAB. The following sample code will generate a sine curve. Figure 1.9(a) shows the plot generated by MATLAB.

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y);

Figure 1.9. Single and Multiple Plots

Axes and Labels

Notice that the plot generated by the above set of commands does not generate any axes labels or a title. These can be added by using following set of commands.

xlabel(‘X-axis’)
ylabel(‘Y-axis’)
title(‘Plot of Y = sin(x)’)

Multiple Plots on the Same Figure

To show how to put several plots on the same figure, a second line, given by y = 0.5sin(x + 1), will be plotted on the same figure. The following code can be used for this operation.

clc
clear
x = 0:pi/100:2*pi;
y = sin(x);
y2 = 0.5*sin(x+1);
plot(x,y);
plot(x,y,x,y2,‘--’);
xlabel(‘X-axis’)
ylabel(‘Y-axis’)
title(‘Plot of Y = sin(x)’)

The clc and clear commands are introduced above. The clc command removes the content of the workspace, while the clear command clears the memory of MATLAB. Figure 1.9(b) shows the plot generated by MATLAB.

Generating Legends for the Plot

In Fig. 1.9(b), the legend has been added using the following command.

legend(‘sin(x)’,‘0.5*sin(x+1)’)

Printing and Saving Plots

Once the plot is ready, it can either be saved in a computer file or be printed. Here is an example of how to perform these two operations. To print the plot, click on the File menu, as shown in Fig. 1.10. A column menu will appear. By clicking on the Print item on this column menu, the plot will be printed. On the same column menu is the Export Setup item. This dialog window provides options to specify attributes of the output file (e.g., the figure size, fonts, line width, and format). One click on this item will yield a standard save window. Two things need to be done in that window. First, name the file and, second, choose the file format of the picture, such as jpg, bmp or eps.

Figure 1.10. Printing and Saving

1.5.2 Special Plots: Contour, Scatter, fplot

In the previous subsection, some MATLAB basic plotting techniques were used. In this subsection, some specialized plotting techniques available in MATLAB will be discussed.

Contour Plot

The contours of an equation can be plotted using the contour command. The contours of an ellipse given by the equation 3X2 + 4Y 2 = C will be plotted, where C can take on different values. It is also possible to generate and plot contours for specific given values of C. The following sample code will generate the required contour plot, and the actual plot is shown in Fig. 1.11(a).

[X,Y] = meshgrid(-5:.5:5,-5:.5:5);
Z = (3*X.^2+4*Y.^2);
[C,h] = contour(X,Y,Z,5);
xlabel(’X-axis’)
ylabel(’Y-axis’)
title(’The contour plot of 3*X^2+4*Y^2 = C’)

Figure 1.11. Contour and Scatter Plots

Note that the dimensions of the quantities X, Y, and Z are automatically determined by MATLAB.

Scatter Plot

The plot command generates a smooth curve passing though all the points that are represented by vectors x and y. The scatter command will generate markers at the locations specified by the vectors x and y, instead of a curve. The code below will generate a scatter plot for the sine curve.

x = 0:pi/20:2*pi;
y = sin(x);
scatter(x,y);
xlabel(’X-axis’)
ylabel(’Y-axis’)
title(’Plot of Y = sin(x)’)

Figure 1.11(b) shows the scatter plot generated using this code.

fplot: Function Plots

The special command fplot plots a function between specified limits. The function must be specified as y = f (x). It is required to specify the two end points for x. The sample code for generating a parabola given by y = x2 + 10 is given here. The plot generated by the fplot command is given in Fig. 1.12(a).

fplot(’x^2+10’,[-20 20])
xlabel(’X-axis’)
ylabel(’Y-axis’)
title(’The function plotted using fplot’)

Figure 1.12. Function and Mesh Plots

1.5.3 3-D Mesh and Surface Plots

Thus far, some of the two dimensional plotting techniques available in MATLAB have been discussed. Next, our attention is focused on some of the three dimensional plotting techniques.

Mesh Plot

Up to this point, plots have been demonstrated that are made of curves. The mesh plot generates a surface specified by the matrices X, Y, and Z. Plot the sine function using the mesh command. The mesh plot of the sine function can also be seen in the MATLAB help manual. The sample code for this plot is as follows.

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z)
xlabel(’X-axis’)
ylabel(’Y-axis’)
zlabel(’Z-axis’)
title(’Mesh plot’)

The mesh plot is illustrated in Fig. 1.12(b). MATLAB also has a command called surf to generate surface plots. Replace the mesh command in the above sample code with the surf command. The reader is encouraged to practice thesurf command.

1.5.4 Using the Plot Editing Mode

Some of the frequently used commands for generating plots in MATLAB have been discussed. Next, practice editing a plot using the options available on the plot window. These editing options are shown in Fig. 1.13. The plot window is shown at the top of Fig. 1.13. The bottom part of this figure explains each of these editing options, and will enable the user to edit the plots for reports or live presentations.

Figure 1.13. Plot Editing Mode

1.6 Optimizing with MATLAB

This section provides a basic guide for solving numerical optimization problems using MATLAB. The MATLAB Optimization Toolbox provides the capability to solve a wide variety of optimization options, such as constrained and unconstrained problems, or linear and nonlinear problems. This section assumes previous familiarity with the basics of numerical optimization, and also with using MATLAB script files and functions (see Sec. 1.3). Before proceeding,please ensure that the MATLAB Optimization Toolbox is installed on the computer. To verify that the Optimization is indeed installed, open MATLAB and click the APPS tab (Fig. 1.1) at the top menu of the MATLAB window. The “Toolboxes” item should contain “Optimization” listed along with any other installed toolboxes.

Using the MATLAB Optimization Toolbox, it is possible to solve (i) nonlinear optimization and (ii) linear optimization problems. Chapter 5 provides the pertinent basic knowledge.

1.7 Popular Functions and Commands, and More

This section provides a list of functions and commands, as well as other general information. This list is presented in Tables (1.1 - 1.17) at the end of this chapter. This list will be useful for writing MATLAB programs. To know exactly how to use a given command or function, simply type help followed by the item in question. In addition, use the help command that is in the table title to obtain general related information.

Table 1.1. Arithmetic Operators (help ops)



Command

Symbol

Description


plus

+

Addition

uplus

+

Unary addition

minus

-

Subtraction

uminus

-

Unary minus

mtimes

*

Matrix multiplication

times

.*

Array multiplication

mldivide

\

Left matrix divide

mrdivide

/

Right matrix divide

ldivide

.\

Left array divide

rdivide

./

Right array divide

mpower

Matrix power

power

.∧

Array power



Table 1.2. Logical Operators (help ops)



Command

Symbol

Description


eq

==

Equal

ne

~=

Not equal

lt

<

Less than

gt

>

Greater than

le

<=

Less than or equal

ge

>=

Greater than or equal

and

&

Logical AND

or

|

Logical OR

not

~

Logical NOT

xor

N/A

Logical Exclusive OR

any

N/A

True if any element of vector is nonzero

all

N/A

True if all elements of vector are nonzero



Table 1.3. Special Characters (help ops)



Command

Symbol

Description


colon

:

Colon

punct

..

Parent directory

punct

%

Comment

punct

=

Assignment

transpose

Transpose



Table 1.4. Program Control Flow Constructs (help lang)



Command

Description


if

Conditionally execute statement

else

If statement condition

elseif

If statement condition

end

Terminate scope for while, switch, try, and if statement

for

Repeat statement for a specific number of times

while

Repeat statement for indefinite number of times

break

Terminate execution of for or while loop

continue

Pass control to the next iteration of for or while loop

switch

Switch among several cases based on an expression

case

switch statement case



Table 1.5. Scripts, Functions and Variables (help lang)



Command

Description


global

Define global variable

mfilename

Name of currently executing M-file

exist

Check if variable or function are defined

isglobal

True for global variable



Table 1.6. Argument Handling (help lang)



Command

Description


nargin

Number of function input argument

nargout

Number of function output argument



Table 1.7. Message Display (help lang)



Command

Description


error

Display error message and abort function

warning

Display warning

disp

Display and array

fprintf

Display formatted message

sprintf

Write format data to a string



Table 1.8. Elementary Matrices (help elmat)



Command

Description


zeros

Zeros array

ones

Ones array

eye

Identity matrix

rand

Uniformly distributed random numbers

randn

Normally distributed random numbers

linspace

Linearly spaced vector

logspace

Logarithmically spaced vector

meshgrid

x and y array for 3D plot

:

Regularly spaced vector and index into matrix



Table 1.9. Basic Array/Matric Information (help elmat)



Command

Description


size

Size of matrix

length

Length of vector

ndims

Number of dimensions

numel

Number of elements

isempty

True for empty matrix

isequal

True of arrays are identical

diag

Diagonal matrices

find

Find indices of nonzero elements

end

Last index



Table 1.10. Special Variables and Constants (help elmat)



Command

Description


ans

Most recent answer

eps

Floating-point relative accuracy

realmax

Largest positive floating-point number

realmin

Smallest positive floating-point number

pi

3.14159263

i, j

Imaginary unit

inf

Infinity

Nan

Not-a-number

isnan

True for not-a-number

isinf

True for infinite elements

isfinite

True for finite elements

why

Succinct number



Table 1.11. Trigonometric Functions (help elfun)



Command

Description


sin

Sine

sinh

Hyperbolic sine

asin

Inverse sine

asinh

Inverse hyperbolic sine

cos

Cosine

cosh

Hyperbolic cosine

acos

Inverse cosine

acosh

Inverse hyperbolic cosine

tan

Tangent

tanh

Hyperbolic tangent

atan

Inverse tangent

atan2

Four quadrant inverse tangent

atanh

Inverse hyperbolic tangent

sec

Secant

sech

Hyperbolic secant

asec

Inverse secant

asech

Inverse hyperbolic secant

csc

Cosecant

csch

Hyperbolic cosecant

acsc

Inverse cosecant

acsch

Inverse hyperbolic cosecant

cot

Cotangent

coth

Hyperbolic cotangent

acot

Inverse cotangent

acoth

Inverse hyperbolic cotangenet



Table 1.12. Exponential and Complex Functions (help elfun)



Command

Description


exp

Exponential

log

Natural logorithm

log10

Common (base 10) logorithm

sqrt

Square root


abs

Absolute value

angle

Phase angle

complex

Construct complex data from real and imaginary part

imag

Complex imaginary part

real

Complex real part

isreal

True for real array



Table 1.13. Rounding and Remainder (help elfun)



Command

Description


fix

Round toward zero

floor

Round toward minus infinity

ceil

Round toward plus infinity

mod

Modulus (signed remainder after division)

rem

Remainder after division

sign

Signum



Table 1.14. Specialized Math Functions (help specfun)



Command

Description


cross

Vector cross product

dot

Vector dot product



Table 1.15. Matrix Analysis (help matfun)



Command

Description


det

Determinant

trace

Sum of diagonal elements

inv

Matrix inverse

eig

Eigenvalues and eigenvectors

svd

Singular value decomposition

expm

Matrix exponential

logm

Matrix logorithm

sqrtm

Matrix square root

fnum

Evaluate general matrix function



Table 1.16. Basic Statistical Operations (help datafun)



Command

Description


max

Largest component

min

Smallest component

mean

Average or mean value

median

Median value

std

Standard deviation

var

Variance

sort

Sort in ascending order

sortrows

Sort rows in ascending order

sum

Sum of elements

prod

Product of elements

hist

Histogram

histc

Histogram count

trapz

Trapezoidal numerical integration

cumsum

Cumulative sum of elements

cumprod

Cumulative product of elements



Table 1.17. Optimization Functions



Command

Description


bintprog

Binary integer programming problems

fgoalattain

Multiobjective goal attainment problems

fminbnd

Minimum of single-variable function on fixed interval

fmincon

Minimum of constrained nonlinear multivariable function

fminimax

Minimax constraint problem

fminsearch

Minimum of unconstrained multivariable function

using derivative-free method

fminunc

Minimum of unconstrained multivariable function

fseminf

Minimum of semi-infinitely constrained multivariable

nonlinear function

ktrlink

Minimum of constrained or unconstrained nonlinear

multivariable function using KNITRO

linprog

Linear programming problems

quadprog

Quadratic programming problems



1.8 Summary

In order to fully realize the power of computational Design Optimization, it is important to implement optimization methods through pertinent computer-based mathematical tools. MATLAB is one such mathematical tool that has gained notorious popularity in the science and engineering community over the last two decades, owing to the diverse set of mathematical functions that it provides and its ease of use (i.e., user-friendliness). To facilitate effective use of MATLAB for implementing the modeling, analysis, and optimization techniques presented in this book, this chapter provided an important introduction to the MATLAB software. Specifically, it provided brief descriptions of the modular MATLAB interface, basic matrix handling and mathematical operations in MATLAB, and the GUI capabilities (e.g., plotting functions) of MATLAB. The chapter ended with a comprehensive set of tables listing some of mostuseful classes of in-built functions available in MATLAB - from logical operators to equation solving functions. For those who are already proficient in MATLAB, this chapter may serve as a convenient reference.

1.9 Problems

Warm-up Problems

1.1(a)Create a folder on your computer and name it after your last name.

(b)Set the Current Directory of MATLAB to the directory created in Part (a).

(c)Create and save an empty M-file in this directory, and name it after your first name.

(d)Undock the Current Directory Window from the MATLAB Desktop and take a screen shot of this directory. Turn in this screen shot.

1.2Start MATLAB.

(a)Define the array z=[1/6 3/4 2/9] in the Command Window.

(b)Using the help browser, find the command that can be used to change the (1) format, and (2) spacing of the numeric output of the above array in the Command Window.

(c)Find the commands that can be used to print (1) the complete contents in the Command Window, and (2) a selection of the contents in the Command Window.

(d)Give at least two examples each for different format and spacing commands available in MATLAB for the array z.

(e)For each example, print z and turn in the output displayed in the Command Window.

1.3(a)Create two arrays A and B (4x2 and 2x4, respectively) in the Command Window. You can randomly choose elements in A and B.

(b)From the Command History browser, create an M-file that includes the definitions of A and B.

(c)In this M-file, compute the following: (1) A*B, (2) B*A (3) Is A*B = B*A? What property of matrix multiplication can be recalled with the help of this example? Comment on these observations in about two lines.

(d)Change all the values of the array elements of A and B using the Variable Editor in the MATLAB Desktop environment to any values of your choice.

(e)Repeat Parts (a) through (c) for the new Aand B.

(f)Submit the M files, the output in the Command Window, and screen shots of the Variable Editor before and after modifying the values.

1.4(a)In the Command Window, create an array, x, such that x ranges from 0 to 10.

(b)Compute four arrays: y1=sin(x), y2=exp(x), y3=x^2+2x+1, and y4=x^3+5 in the Command Window. You need to make sure that the sizes of x and y are the same.

(c)Save all the arrays computed in Parts (a) and (b) on your hard drive as .mat files.

(d)Write an M-file that loads these .mat files from your hard drive.

(e)In the same M-file, add a code to plot the arrays y1, y2 y3 and y4 against x, all in the same plot, with different line styles. Make the plots look professional. Add your name, title, axes legends, and labels to the plot.

(f)Identify which factors impact the smoothness of the above plotted curves. Create four new figures, each showing the plots of y1, y2, y3, and y4, respectively, as a function of x. In each figure, show at least three plots with increasing curve smoothness. Discuss your results in three to four lines. The objective here is to develop your understanding of what is sufficient to obtain a visually smooth curve in practice.

(g)Submit the M-file, plots, and the discussions.

1.5Generate the following matrices: A = [2 4 6;3 5 1;7 5 9],

B = [1 3 6], and C = [5;7;2;0].

(a)Generate a matrix D = [A;B].

(b)Now generate a new matrix E = [D C].

(c)Find the determinant of matrix E.

(d)Find the inverse of matrix E.

(e)Find the transpose of matrix E.

(f)Define a new matrix F = [3;17;12;-2].

(g)Define another matrix H = [5 7 4 -2;3 12 -6 14].

(h)Explain whether or not the following matrix multiplications are possible: (1) EE, (2) FF, (3) HH, (4) EF, (5) FE, (6) HE, (7) EH, (8) FH and (9) HF.

(i)In the cases for which multiplication is possible, perform it using MATLAB. Turn in a print out of your results (from the Command Window) of Parts (a) through (e), and (h).

1.6For the matrix A = [2 4 6;3 5 1;7 5 9] given in the above problem, determine the eigenvalues and eigenvectors. Turn in a print out of your results (from the Command Window).

1.7Generate the following matrices:

A = [12 14 16 40; 32 15 11 1; 7 25 19 10],

B = [9 1 36 4; 19 0 -31 2], and C = [7; 5; 7; 2; 0].

(a)Generate a matrix D = [A;B].

(b)Now generate a new matrix E = [D C].

(c)Find the determinant of matrix E.

(d)Find the inverse of matrix E.

(e)Find the transpose of matrix E.

(f)Define a new matrix F = [16;3;17;12;-2].

(g)Define another matrix H = [5 7 4 -2 -1;-9 3 12 -6 14].

(h)Give reasons: which of the following matrix multiplications are possible - (1) EE, (2) FF, (3) HH, (4) EF, (5) FE, (6) HE, (7) EH, (8) FH and (9) HF.

(i)In the cases for which multiplication is possible, perform it using MATLAB. Submit a printout of your results (from the Command Window) of Parts (a) through (e), and (h).

1.8For the matrices A defined in Problem 1.6 and E defined in Problem 1.7, determine their eigenvalues and eigenvectors. Submit a print out of your results (from the Command Window).

1.9Define the matrices: A = [12 16 4;23 1 21;9 10 1]

and B = [2 7 14;3 11 2;-9 10 12].

(a) Perform matrix multiplication AB.

(b)Perform matrix multiplication BA.

(c)Are the answers from Parts (a) and (b) the same? If yes, explain why. If not, explain why.

(d)Find the inverse of A, and call it matrix X.

(e)Find the inverse of B, and call it matrix Y.

(f)Perform matrix multiplication A*X.

(g)Perform matrix multiplication B*Y.

(h)Are the answers from Parts (g) and (h) the same. If yes, explain why. If not, explain why.

(i)Submit a printout of your results (from the Command Window) for Parts (a) through (h).

1.10Define the matrices A = [12 16 4;23 1 21;9 10 1], B = [2 7 14;3 11 2;-9 10 12], C = [43 12;13 12], and D = [1 2 3;4 5 6].

(a)Perform the following additions: (1) A+B, (2) A+C, (3) A+D, (4) B+C, (5) B+D, and (6) C+D.

(b)Are each of the above additions possible? If yes, explain why. If not, explain why.

(c)Perform the following operations: (1) A+B and (2) B+A. Is the answer to these two additions the same? If not, explain why. If yes, which matrix addition property is demonstrated using these two additions?

(d)Submit a print out your results (from the Command Window) for Parts (a) and (c), and discussions for the Part (b).

1.11Define a matrix A = [12 16 4;23 1 21;9 10 1] and B = [2 7 14;3 11 2;-9 10 12].

(a)Perform matrix multiplication A*B, and call this D.

(b)Find the transpose of A, and call this E.

(c)Find the transpose of B, and call this F.

(d)Find the transpose of D, and call this G.

(e)Perform matrix multiplications: (1) E*F and (2) F*E.

(f)Which of the above two multiplications are the same as the matrix DT?

(g)Which property of the matrix multiplication is demonstrated from Part (f)?

(h)Submit a printout of your results (from the Command Window) for Parts (a) through (g).

1.12Solve the following systems of linear equations and turn in a print out of your results (from the Command Window).

(a) 3x + 4y = 12 and 4x + 2y = 10.

(b)3x + 4y = 12 and 4x = 10.

(c)-4x + y = 14 and 4x + 3y = 10.

(d)13x+12y = -6, -4x+7y = -73, and 11x - 13y = 157.

(e)2x + 3y - z = 8, 4x - 2y + z = 5, and x + 5y - 2z = 9.

(f)4x-8y+3z = 16, -x+2y-5z = -21, and 3x - 6y + z = 7.

(g)2a + 3b + c - 11d = 1, 5a - 2b + 5c - 4d = 5, a - b + 3c - 3d = 3, and 3a + 4b - 7c + 2d = -7.

1.13Write a simple MATLAB program in an M-file that generates a 1 x 25 array called A, where A = [1 2 3 4 ... 25]. Use for loop logic. Turn in a printout of your M-file and the command prompt output after running the M-file.

1.14Write an M-file that tests whether two numbers are greater than zero. If both are greater than zero, then the program should print ‘Both’ on the screen. If neither of them is greater than zero, then the program should print‘None’. For any other case, the program should print ‘Other’. Submit a printout of your M-file. Run your M-file for two cases, and submit a printout of the command prompt output.

1.15This problem will test your MATLAB programming skills.

(a)Write an M-file that defines a row vector of 50 elements with all ones.

(b)Add a code that replaces every element that is in an even place (for example the 2nd, 4th, 6th,...) with the number 2.

(c)Add a code that replaces every element that is in a place divisible by three (for example the 3rd, 6th, 9th,...) with the number 3.

(d)Turn in a printout of the final M-file and the output after running Parts (a) through (c).

1.16Write an M-file to generate three contour plots of 3x2 + 4y2 = C, where 1 ≤ x ≤ 2 and 3 ≤ y ≤ 5 . The first, second, and third plots should contain 2, 5, and 7 contours, respectively. Using the same M-file, also generate a scatter plot for 3x2 + 4y2 = 20. Turn in the M-file and the plots.

1.17Write an M-file to plot y = 4x + 10, and y = 4x2 + 10 for 1 ≤ x ≤ 5 on the same graph. Provide appropriate X and Y axis labels and the legend. All the labels and legends must be Times New Roman font and the font size must be 15. The font type and font size of these labels and legends must be changed through your M-file. Turn in your M-file and the plot.

1.18Learn about the subplot command. You can refer to the MATLAB tutorial available on www.mathworks.com. Write an M-file to plot y = 4x + 10, y = 4x2 + 10, and y = sin(x) for 0 ≤ x ≤ 3.5 on the same plot. Now plot these three curves on different subplots using the subplot command. Every subplot should contain individual titles, axis labels, and legends. Turn in the M-file and the plots.

1.19Learn about about the peaks command. You can refer to the MATLAB tutorial available on www.mathworks.com. Now write an M-file to generate a 3D plot of the peaks command using mesh and surf. The plot should contain a title, axis labels, and legends. Through your M-file, write your first name on the top-left corner of this plot, and your last name just below the peaks that appear in the plot. Turn in your M-file and the plots.

Intermediate Problems

1.20This problem will test your ability to use M-files.

(a)Write a function file in MATLAB that takes in one input and returns a single output. Call the function getSquared. The function should output the square of the number that it takes as input. Remember that the function must actually RETURN the squared value, and not simply display it on screen. Save the function file in some directory that you created. Turn in a printout of the function file.

(b)Write a script M-file called testSquared.m that defines a variable called xinput. Give any numerical value to xinput. From within this M-file, call the function getSquared. Store the output from the function file in a newvariable called xoutput. Write a statement in the M-file that will print both the xinput and xoutput on the screen. Save the script M-file in the same folder as the function file. Turn in a printout of the M-file.

(c)Run the file testSquared.m from the command prompt. Turn in a printout of the output you get.

(d)Run the function file getSquared.m from the command prompt to calculate the square of any variable in your workspace. If you do not have one, create it in the workspace. Turn in a printout of your command promptoutput.

(e)Save your getSquared.m function as getSquaredSpecial.m. Modify this function. Add a test code in your new function to determine whether the input number is greater than or equal to zero. If yes, then the function does exactly what it did before (that is, squaring). If not, then the function simply returns the value -1. Turn in a printout of your getSquaredSpecial.m file.

(f)In a similar fashion as above, create the function testSquaredSpecial.m file. Run two cases: (i) xinput is a positive number, and (ii) xinput is a negative number. Turn in a printout of the command prompt output for both cases.

1.21This problem will test your skills in structured programming using flow control statements.

(a)Write a function called sumHundred that takes an integer as the input. The function should determine whether the input is an integer between 1 and 100. If not, the function should display an appropriate error message. Turn in a printout of the function file.

(b)Test the function from the command prompt using (i) a number between 1 and 100, and (ii) a number greater than hundred. Turn in a printout of the command prompt output for both cases.

(c)You will now modify your function sumHundred. Add some logic to it using for or while loops, such that the function evaluates the sum of all integers from 1 to the input number. For instance, if the input number is 79, it should evaluate the sum of the first 79 integers. Do not use any built-in MATLAB functions. Turn in a printout of the modified function file. Run two test cases from the command prompt and turn in a printout of the results along with the M-file.

(d)Save your sumHundred function as sumEvenHundred. Add another logic code to the original function, such that now it evaluates the sum of all even integers from 1 to the input number. For instance, if the input number is 51, it should evaluate the sum of the even integers between 1 and 51. Turn in a printout of the function file and run it for two test cases from the command prompt. Turn in a printout of the results.

1.22This problem will test your variable handling skills.

(a)Write a function called hiddenSum that takes two inputs and returns the sum of the two inputs. Turn in a printout of the function.

(b)Write a script M-file called testHiddenSum.m that defines two variables x and y. Assign some values to these variables. Call the function hiddenSum from within this script M-file and store the result in a local variable, z. Run the script M-file and turn in a printout with the value of z.

(c)Modify the function hiddenSum such that now it DOES NOT HAVE any output arguments. Now modify your script M-file such that it calls hiddenSum using x and y as inputs and assigns the result to the variable z. You will need to further modify your function file. Submit a printout of the new function and script files and command prompt results from running your script M-file.

(d)Now modify your function hiddenSum such that it DOES NOT HAVE any input OR output arguments. Modify your script M-file such that it calls hiddenSum using x and y as inputs, and stores the result in the variable z.You will need to further modify your function file. Submit a printout of the new function and script files, and the command prompt results from running your script M-file.

Table 1.18. Equation Solving Functions



Command

Description


fsolve

Solve system of nonlinear equations

fzero

Find root of continuous function of one variable



Table 1.19. Least Squares (Curve Fitting)



Command

Description


lsqcurvefit

Solve nonlinear curve-fitting problems in least-squares sense

lsqlin

Solve constrained linear least-squares problems

lsqnonlin

Solve nonlinear least-squares problems

lsqnonneg

Solve nonnegative least-squares constraint problem



BIBLIOGRAPHY OF CHAPTER 1

[1]M. S. Bazaraa, H. D. Sherali, and C. M. Shetty. Nonlinear Programming: Theory and Algorithms. John Wiley and Sons, 3rd edition, 2013.

[2]A. Ravindran, G. V. Reklaitis, and K. M. Ragsdell. Engineering Optimization: Methods and Applications. John Wiley and Sons, 2006.

[3] G. R. Lindfield and J. E. Penny. Numerical Methods: Using MATLAB. Academic Press, 2012.

[4]The MathWorks, Inc. www.mathworks.com.

[5]The MathWorks, Inc. MATLAB Graphics. 2014. www.mathworks.com/help/pdf_doc/matlab/graphg.pdf.

[6]T. A. Davis. MATLAB Primer. CRC Press, 8th edition, 2011.

[7]A. Knight. Basics of MATLAB and Beyond. CRC Press, 2000.

[8]R. Pratap. Getting Started with MATLAB: A Quick Introduction for Scientists and Engineers. Oxford University Press, 2009.

[9]J. J. Moré and S. J. Wright. Optimization Software Guide. Frontiers in Applied Mathematics - 14. SIAM, 1993.

[10]Vanderplaats Research and Development, Inc. GENESIS structural analysis and optimization software. www.vrand.com.

[11]MSC/Nastran. Structural optimization software. www.macsch.com.

[12]Altair Corp. Structural optimization software. www.altair.com.

[13]D. Xue and Y. Chen. Solving applied mathematical problems with MATLAB. CRC Press, 2011.