2

Basics

Abstract

In the 1970s, a special computer tool was developed for mathematicians. The tool and its language were named MATLAB®; the term is designed from the three first letters of the two words ‘matrix’ and ‘laboratory’ to emphasize the main element of this language: a matrix. This matrix-based approach unifies the calculating procedures for both algebraic and graphical processing. Within a short course, MATLAB® was adapted and became a convenient tool for technical computing, to the extent that today, engineers use it for quality assurance (QA) in a variety of QA calculations.

In this chapter, the tool desktop and their windows are presented; the starting procedure is introduced; the main commands for simple arithmetical, algebraic, matrix and array operations are described; and finally, the basic loops and relational and logical operators are explained.

Key words

MATLAB® Desktop

windows

functions

commands loop

logical operators

quality assurance

2.1 Starting with MATLAB® software1

Application programs and computers themselves are managed by a set of special programs called the ‘operating system’, OS. These programs may be different for different groups of computers. Here we assume that MATLAB® is installed on a personal computer with the Windows OS. To launch MATLAB®, click on the icon u02-45-9780857094872 that displays a red L-shaped membrane (Figure 2.1); this icon is placed on the Windows Desktop and on the Quick Launch bar. Alternately, it is possible to start MATLAB® by finding and clicking on the matlab.exe file in the bin- directory; the path to this file is C:Program FilesMATLABR2012ain matlab.exe.

f02-01-9780857094872
Figure 2.1 MATLAB® L-shaped membrane, obtained with the logo command1

2.1.1 MATLAB® Desktop and its windows

The window that appears after starting the program is the MATLAB® Desktop (Figure 2.2). The desktop includes the toolstrip and four windows: Command, Current Folder, Workspace, and Command History.

f02-02-9780857094872
Figure 2.2 MATLAB® R2012b Desktop
Toolstrip

The toolstrip contains the main MATLAB® purpose operations and functions, presented in three global tabs: the Home, Plots and Apps. Tabs are divided into sections that contain a series of related controls: buttons, drop-down menus and other user interface elements (Figure 2.3). The tabs include a number of buttons that are grouped in sections according to functionality (file, variable, code, etc.); the sections include buttons for the execution of various operations (e.g., Open, New Variable, Preferences, etc.). The Home tab (Figure 2.3) is the tab used most intensively and includes general purpose operations, such as creating new files, importing data, managing your workspace, and the settings of the Desktop layout. The Plots tab displays a gallery of plots available in MATLAB® and any toolboxes that you have installed. The Apps tab contains a gallery of applications from the toolboxes.

f02-03-9780857094872
Figure 2.3 The Desktop toolstrip

The quick access toolbar is located to the right of the top of the strip; this toolbar contains frequently used options such as cut, copy, paste, etc. The Search Documentation box is located next to the quick access toolbar; it enables you to search for documentation about commands and other topics of interest.

The line with the current folder toolbar is placed on the bottom of the strip; this toolbar controls the directory currently working.

Desktop windows

 Command Window is the main component of the desktop where the commands are entered and the result of their execution is displayed. For convenience, the window can be separated from the desktop, by choosing the u02-01-9780857094872 Undock line of the Show Command Window Actions button u02-02-9780857094872 to the right of the window title bar. It is possible to separate all desktop windows. To assemble separated windows click on u02-03-9780857094872 or select the Default line in the Desktop Layout of the desktop Menu option.

 Workspace Window is the graphic interface, showing icons of variables and other objects currently located in the MATLAB® workspace; it also displays the class of each variable and its values, which are automatically updated with calculations.

 Current Folder Window presents a browser that shows the full path to the current folder, and shows the contents of the current folder. When starting MATLAB® here, we can view the starting directory, called startup directory, and the files and folders located there. After selecting the file, information about it appears in the Details panel.

 Command History Window keeps most commands entered in the Command Window; it shows the times and dates with a list of the commands and statements that have been run in current and earlier sessions.

The above windows are used intensively; in addition to these windows are Help, Editor, and Figure windows, which do not appear by default when opening the desktop; they are described within the chapters where they are used.

2.1.2 Elementary functions and interactive calculations

There are two ways to run commands in MATLAB®: interactively and with m-files. The interactive way is briefly presented here, while the second will be explained later.

To enter and execute a command, it must be typed in the Command Window immediately after the command prompt >>, which indicates the place to type the command. Figure 2.4 presents some elementary commands entered in the Command Window.

f02-04-9780857094872
Figure 2.4 Command Window after separation from the desktop

The symbol u02-04-9780857094872, which appears by default to the left of the command prompt, is called the Function Browser button. It helps find the needed commands and information about its syntaxes and usage.

Entering a command and manipulating with it require us to master the following rules:

 the command must be typed next to the prompt >>;

 the Enter key must be pressed to execute the command;

 a command in a preceding line cannot be changed; to correct or repeat an executed command press the up-arrow key ↑ ;

 a long command can be continued on the next line by typing . . . - three periods; the total length of a line should not be more than 4096 characters for one command;

 commands in the same line should be divided by semicolons (;) or by commas (,);

 a semicolon at the end of the command withholds displaying the answer;

 the symbol % (percent symbol) designates the comments that should be written after it in the line; the comments are not executed after entering;

 the clc command clears the Command Window.

The Command Window can be used as a calculator by using the following symbols for arithmetical operations: + (addition), − (subtraction),* (multiplication), / (right division), (left division, used mostly for matrices), ^ (exponentiation).

These operations are applicable to a wide variety of elementary, trigonometric and specific mathematical functions, which should be written as the name and the argument in parentheses, e.g., sin x should be written as sin(x); in trigonometric functions, the argument x should be given in radians; in trigonometric functions written with the ending letter ‘d’, e.g., sind x, the argument x should be written in degrees; inverse trigonometric functions with the ending ‘d’ produce the result in degrees. A short list of such functions and variables is given in Table 2.1. Hereinafter, the operations executed in the Command Window are written after the command line prompt (>>); this also conveys that the user should press the Enter key after entering one or more commands written in one command line.

Table 2.1

Elementary, trigonometric, and specific mathematical functions

Functions and constants in MathMATLAB® presentationMATLAB® example (inputs and outputs)
|x| – absolute valueabs(x)>> abs(− 15.1234)
ans = 15.1234
ex – exponential functionexp(x)>> exp(2.7)
ans = 14.8797
ln x – natural (base e) logarithmlog(x)>> log(10)
ans = 2.3026
log10x – Napierian (base 10) logarithmlog10(x)>> log10(10)
ans = 1
x – square rootsqrt(x)>> sqrt(2/3)
ans = 0.8165
π – the number π (circumference-todiameter ratio of circle)pi>> 2*pi
ans = 6.2832
n! – factorial; product of the integers from 1 to nfactorial(n)>> factorial(5)
ans = 120
Round towards minus infinityfloor(x)>> floor(− 12.1)
ans = − 13
Round to the nearest integerround(x)>>round(12.6)
ans = 13
sin x – sinesin(x)>> sin(pi/3)
ans = 0.8660
sind x – sine with x in degreessind(x)>> sind(60)
ans = 0.8660
cos x – cosinecos(x)>> cos(pi/3)
ans = 0.5000
cosd x – cosine with x in degreescosd(x)>> cosd(60)
ans = 0.5000
tan x – tangenttan(x)>> tan(pi/3)
ans = 1.7321
tand x – tangent with x in degreestand(x)>> tand(60)
ans = 1.7321
cot x – cotangentcot(x)>> cot(pi/3)
ans = 0.5774
cotd x – cotangent with x in degreescotd(x)>> cotd(60)
ans = 0.5774
arcsin x – inverse sineasin(x)>> asin(1)
ans = 1.5708
arcsind x – inverse sine with x between − 1 and 1; result in degrees between − 90° and 90°asind(x)>> asind(pi/6)
ans = 31.5740
arccos x – inverse cosineacos(x)>> acos(1)
ans = 0
arccosd x – inverse cosine with x between − 1 and 1; result in degrees between 0° and 180°acosd(x)>> acosd(pi/6)
ans = 58.4260
arctan x – inverse tangentatan(x)>> atan(1)
ans = 0.7854
arctand x – inverse tangent; result in degrees between − 90° and 90° (asymptotically)atand(x)>> atand(pi/6)
ans = 27.6365
arccot x – inverse cotangentacot(x)>> acot(1)
ans = 0.7854
arccotd x – inverse cotangent; result in degrees between − 90° and 90°acotd(x)>> acotd(pi/6)
ans = 62.3635
Γ(x)=0ettx1si1_e -gamma functiongamma(x)>> gamma(5)
ans = 24
erf(x)=2π0et2dtsi2_e -error functionerf(x)>> erf(3/sqrt(2))
ans = 0.9973

The result of entering a command is a variable with the name ans. The sign equal (=) is called the assignment operator and is used to specify a value to a variable, e.g., to the ans. An entered new value cancels its predecessor.

Arithmetic operations are performed in the following order: operations in parentheses (starting with the innermost), exponentiation, multiplication and division, addition and subtraction. If the expression contains operations of the same priority, they run from left to right.

Examples of arithmetical operations in the Command Window are given below:

u02-05-9780857094872

The outputted numbers are displayed here in short format (default format) - a fixed point followed by four decimal digits. The format can be changed to long, fourteen digits after the point, by typing the command: format long. To return to the default format, type format (additional information on formats is given in Subsection 2.1.6).

2.1.3 Help commands and Help Window

For information about use of a command, type and enter help with the command name after a space next to this word, e.g., help format, as in the preceding subsection. The explanations appear immediately, in the Command Window. For a command concerning a topic of interest the lookfor command may be used. For example, for the name of MATLAB® command/s on the subject of Pareto charts and distribution one should enter lookfor Pareto and after a rather long search the commands will appear on the screen, as shown below (incomplete):

u02-06-9780857094872

For further information, click on the selected command or use the help command. To interrupt the search process, the two abort keys Ctrl and C should be clicked together; these keys should also be used for interruption of any other process, e.g., that of a program/command execution. Note:

 The information returned by the lookfor command can differ on different computers, as this is determined by the toolbox set installed with MATLAB®, e.g., for the request about the paretotails command, the Statistics Toolbox™ should be installed on your computer.

 In cases when the subject you are searching for has two or more words, they should be written between the quotes, for example, lookfor ‘linear regression’.

For more detailed information one can similarly use the doc command, e.g., doc pareto, in which case the Help Window will open (Figure 2.5). The latter window can be opened in other ways, for example, by selecting the Documentation line in the Help option u02-07-9780857094872 on the toolstrip of the Resources group of the desktop Home tab.

f02-05-9780857094872
Figure 2.5 Help Window with information about the pareto command

When the Help Window is opened with the doc command, the Help Window comprises the menu line, the Search Documentation field, the Table of Contents button u02-08-9780857094872 on the line with documentation chapters containing the searched topic, and search results with the information on the subject.

Information can also be obtained by typing the word/s into the Search Documentation line at the top of the window. In this case, the Help Window contains two panes:

 the Refine pane (to the left) for filtering the defined information by product, category or type;

 the Results pane (to the right) with a preview of defined information, the toolbox name for which the information is relevant and an icon denoting the type of document in which the search words were found, for example, the u02-09-9780857094872 icon designates an example page.

2.1.4 About toolboxes

While sin, cos, sqrt, log, and other MATLAB® functions are valid in a wide range of sciences - from aeronautics to medicine - specialized commands are needed in each area for solving problems specific to that field. For these purposes, the basic and problem-oriented tools are assembled in so-termed toolboxes, e.g., basic commands discussed thereafter are assembled in the MATLAB® toolbox, commands related to statistics in the Statistics toolbox, commands to signal processing in the Signal Processing toolbox, commands for neural networks in the Neural Network toolbox, etc. Use the ver command to verify which toolboxes are available on your computer. When this command is typed and entered in the Command Window, the header with product information and a list of toolbox names, versions, and releases is displayed, as follows:

>> ver
---------------------------------------------------------------------------------
MATLAB Version: 8.0.0.783 (R2012b)
MATLAB License Number: 671014
Operating System: Microsoft Windows 7 Version 6.1 (Build 7601: Service Pack 1)
Java Version: Java 1.6.0_17-b04 with Sun Microsystems Inc. Java
HotSpot(TM) 64-Bit Server VM mixed mode
---------------------------------------------------------------------------------
MATLABVersion 8.0(R2012b)
SimulinkVersion 8.0(R2012b)
Aerospace ToolboxVersion 2.10(R2012b)
Bioinformatics ToolboxVersion 4.2(R2012b)
. . .

t0040

The list was interrupted, as it can be quite long, depending on the installed toolboxes. The information about available toolboxes can also be obtained from the pop-up menu that appears after clicking the Start button on the bottom line of the MATLAB® Desktop (see Figure 2.2).

2.1.5 Variables, their names, and commands to variable management

A variable is a symbol, namely letter/s and number/s, to which some specific numerical value is assigned. MATLAB® allocates space in the computer’s memory for storage of the variable names and their values. It is possible to assign a single number (a scalar), or a table of numbers (an array) to a variable. The name can be as many as 63 characters long, and contain letters, digits and underscores, the first character being a letter. Existing command names (sin, cos, sqrt, etc.) are not recommended for use as variable names, because they would confuse the system.

The following screenshot demonstrates the assignment and use of variables in algebraic calculations:

u02-10-9780857094872

Some variables/constants can be used without a prior assignment, as they are assigned and permanently stored by MATLAB®. Such variables are termed ‘predefined’. In addition to previously mentioned pi and ans, are the predefined variables inf (infinity, the result, for example, of division by zero), i or j (square root of − 1), NaN (not-a-number, used when a numerical value is moot, e.g., 0/0).

The following commands related to variable management can be used: clear - for removing the memory, or clear x y - for removing named variables x and y only; who - for displaying the names of variables or whos - for displaying variable names, matrix sizes, variable byte sizes and variable classes. Moreover, each variable with the same information, as in the case of whos, and those with additional data, is presented in the Workspace Window by the icon u02-11-9780857094872, To select additional information about a variable, click the mouse’s right button with the cursor placed on the Workspace Window menu line; the pop-up menu appears with a list of possible additional information.

2.1.6 Formats for displaying output

MATLAB® displays output on the screen in format specified by the format command, which takes the forms

formatorformatformat_type

si4_e

The first command sets the short type of format, which is also the default format of numeric data. In this format, the four decimal digits are displayed, e.g., 3.1416, the last digit is rounded; when the real number is less than 0.001 or greater than 1000 the number is shown in the shortE format, which uses scientific notations - a number between 1 and 10 multiplied by a power of 10 (e.g., the Boltzmann constant in scientific notations is presented as 1.3807e-023, in JK− 1 and should be read as 1.3807 • 10− 23, and the 3.4e-6 defect level of the Six Sigma process should be read as 3.4 • 10− 6); thus, the number a = 1000.1 is displayed in short or shortE formats as 1.0001e + 003 where e + 003 is 103 and the whole number should be read as 1.0001 • 103. Note, that scientific notations can also be used for inputting variables, e.g., d = 3.4e-6.

The format_type parameter in the second of the format commands is a word that specifies the type of the displayed numbers. Other format types can be used in addition to the short and shortE format types. To show more decimal digits, the display output can be replaced by the long or longE format type. In this case, 15 decimal digits are displayed. For example, when setting the longE format type and inputting Avogadro’ constant 6.0221412927 • 1023, MATLAB® yields the following results:

>> format longE

>> A = 6.0221412927e23

A = 6.022141292700000e23

Note:

 The format commands change the numbers on the display but do not make changes in the computer memory, nor do they affect the type of the inputted numbers.

 Once a certain number format type is specified, all subsequent numbers are displayed within it.

 To return to the replaced short format, the format or format short command should be entered.

 The format_type parameter can be written with a space between short and E and long and E; the capital E can be written as a conventional e.

There are other types of formats that can be used with the format command; more details about these can be obtained by using the help format command.

2.1.7 Commands for displaying output

MATLAB® automatically displays the result after entering a command, but not when the command is followed by a semicolon. The two most frequently used commands for output management are: disp and fprintf.

The disp command displays texts or variable values without the name of the variable and the = (equal) sign. Every new disp command yields its result in a new line. In general form, the command reads

disp(‘Text string’) or disp(Variable name)

The text between the quotes is displayed in blue. For example:

u02-12-9780857094872

The fprintf command is used to display texts and data or to save them in a file. The command has various forms, which present difficulties for beginners, and here we give the simplest of these forms, for displaying calculation results.

For formatted output and displaying text and a number on the same line the following form is used:

u02-13-9780857094872

To display text with a new line, or to divide text on two or more lines the (slash n), write the characters before the word that we want to see on the new line. The same characters should be written to cause the appearance of the >> prompt from the new line after executing the fprintf command. The field width number and the number of digits after the point (6.3 in the presented example) are optional; the sign % and the character f, called conversion characters, are obligatory, e.g., if %f was written instead of % 6.3f, the number will be displayed with 6 digits after the point. The f specifies the fixed point notation in which the number is displayed. Some additional notations that can be used are i (or d) - integer, e - exponential, e.g., 2.309123e + 001, and g - the more compact form of e or f, with no trailing zeros.

The addition of several %f units (or full formatting elements) permits the inclusion of multiple variable values in the text. An example follows using the fprintf command:

u02-14-9780857094872

The color of the text in the quotes is the same as in disp (blue).

Described output commands can be used to display tables; this will be shown later, after studying the vectors, arrays, and matrices (see Subsection 2.2.5).

2.1.8 Application examples

Examples of some simple calculations by mathematical expressions are given below.

2.1.8.1 Bayes’ law

Identical products in a lot are made by manufacturers A, B, and C in the amounts NA = 120, NB = 90, and NC = 107 units; probabilities of defective unit appearance are 0.01, 0.03, and 0.02 for every manufacturer respectively. Probability p(HA|A) that a randomly taken unit is defective and was produced by the manufacturer A can be defined using the Bayes’ equation.

p(HA|A)=NApANApA+NBpB+NCpC

si5_e

Problem: Calculate by the given expression.

The solution:

u02-15-9780857094872

2.1.8.2 Gaussian function

In statistical calculations of various QA problems, the Gaussian function, frequently called normal distribution (see also Subsection 6.2.2), is used:

f(x)=1σ2πe(xμ)2/(2σ2)

si6_e

where x, μ, and σ are a random variable, expectation, and standard deviation respectively, for standard case σ = 1 and μ = 0.

Problem: Calculate f(x) with this expression for standard case and x = 6σ.

The solution:

u02-16-9780857094872

2.1.8.3 Uncertainty in derivation of the gravitational acceleration constant

The relative error Δggsi7_e of the gravitational acceleration constant g derived from experiment with a pendulum with some idealization can be calculated by the following expression (http://en.wikipedia.org/wiki/Experimental_uncertainty_analysis):

Δgg=ΔLL2ΔTT+(θ2)2Δθθ

si8_e

where the pendulum parameters L, in m, T, in s, and θ, in rad, are length, period and initial angle respectively; ΔL, ΔT, and Δθ are the uncertainties of the corresponding values; the (θ2)2si9_e coefficient is dimensionless for θ given in radians.

Problem: The tested pendulum length and its uncertainty are 0.5 and − 0.005 m (underestimated) respectively, the period and its uncertainty are 1.443 and 0.02 sec (overestimated), and initial angle and its uncertainty are 30 and − 5 deg (underestimated). Calculate relatively error in value of the gravitational acceleration constant.

The solution:

>>L=0.5;dL=0.005;>>T=1.443;dT=0.02;>>Teta=30*pi/180;dTeta=5*pi/180;>>dg_rel=dL/L2*dT/T+(Teta/2)2*dTeta/Tetadg_rel=0.0491

si10_e

2.1.8.4 Sample size

To save time, resources and money and to correctly check your product, survey, or data set (also called population), the following expression is frequently used to choose the sample size that provides the required accuracy:

n=z2P(1P)I2

si11_e

where P is the estimated population proportion, I is the confident interval characterizing the accuracy of the estimated parameter, and z is the standard score expressing the deviation from the mean score of the sample; z is 1.96 for α = 0.05.

Problem: Calculate the sample size n when the population of interest has the following parameters: P = 0.6, I = 0.05, z = 1.96; round n with the round command and display as integer number.

Based on the specified parameters, the solution is:

>>P=0.6;>>I=5e2;>>z=1.96;>>n=round(z^2*P*(1P)/I^2);n=369

si12_e

2.2 Vectors, matrices, and arrays

A normal table of numbers, which often represents data in quality sciences, is an array or matrix. The variables that were used heretofore were given in scalar form. Each of these variables is a 1 × 1 matrix in MATLAB®. Mathematical operations with matrices and arrays are more complicated than with scalars: linear algebra operations should be applied for matrices, and element-wise operations for arrays.

2.2.1 Generation of vectors and matrices and vector and matrix operators

Generation of vectors

Vectors are presented as numbers written sequentially in a row or in a column, and termed respectively - row or column vectors. They can also be presented as lists of words or equations. In MATLAB® a vector is generated by typing the numbers in square brackets with spaces or comma between them in the case of a row vector, and with semicolons between them, or by pressing Enter between them, in the case of a column vector.

Say, for example, that the inspector measured the weight of a product by a control plan at different times as per Table 2.2.

Table 2.2

Time–weight data

Time,hour88.38.799.49.71010.33
Weight,g1019610410010298103104

t0015

The data can be presented as two vectors, for example:

u02-17-9780857094872

If there is not enough space to display all the vector elements on one line they are listed in two or more lines with a message informing which column is presented in each line, for example:

u02-18-9780857094872

There are also two frequently used operators for generating vectors, namely ‘:’ (colon) and linspace.

The colon operator has the form

vector_name=i:j:k

si13_e

where i and k are respectively the first and last term in the vector and j is the step between the terms within it. The last number cannot exceed the last term k. The step for j can be omitted; in such a case it is equal to 1 by default. Examples are:

u02-19-9780857094872

The linspace operator has the form

vector_name=linspace(a,b,n)

si14_e

where a is the first number, b is the last number and n is the amount of numbers. When n is not specified, this value is 100 by default. For example:

u02-20-9780857094872

The position of an element in a vector is its address; for example, the fifth position in the eighth element vector Weight above can be addressed as Weight (5), the element located here is 102. The last position in a vector may be addressed with the end terminator, e.g., Weight(end) is the last position in the Weight vector and marks the number located here – 104; another way to address the last element is to give the position of number, namely Weight (8).

Generation of matrices and arrays

A two-dimensional matrix or an array has rows and columns of numbers and resembles a numeric table, the difference manifesting itself only in the realization of certain mathematical operations. When the number of rows and columns is equal, the matrix is called square, otherwise, it is rectangular. Like a vector, it is generated by typing the row of elements in square brackets with spaces or commas between them and with semicolons between the rows, or by pressing Enter between the rows; the number of elements in every row should be equal.

The elements can also be variable names or mathematical expressions.

As an example, Table 2.3 presents repeated ball bearing diameter tests performed on three samples.

Table 2.3

Ball bearing diameter (mm)

Sample 1Sample 2Sample 3
50.151.248.9
50.049.950.1
50.450.650.0
49.950.049.7

Matrix presentation of this table and some other matrix generation examples are:

u02-21-9780857094872

Row-column addressing is used to manipulate with matrix elements. For instance, in matrix A in the previous example, set A(2,3) refers to the number 50.1000 and A(3,2) to the number 50.600. Row or column numbering begins with 1, so that the first element in matrix A is A(1,1).

For sequential elements or an entire row or column, the semicolon can be used, e.g., A(2:3,2) refers to the second and the third numbers in column 2 of matrix A, A(:,n) refers to the elements of all rows in column n, and A(m,:) to those of all the columns in row m.

In addition to row-column addressing, linear addressing can be used. In this case, a single number is used instead of the row and column numbers. The element’s place within the matrix is indicated sequentially, beginning with the first element of and along the first column, then continuing along the second column and so forth, up to the last element in the last column. For example, A(7) refers to element A(3,2), A(10) to A(2,3), A(5:8) is the same as A(:,2), etc.

Using square brackets, it is possible to generate a new matrix by combining an existing matrix with a vector or with another matrix. Examples of this kind are presented below, using matrix A from the previous example.

u02-22-9780857094872

To convert a row/column vector into a column/row one and for the rows/ columns exchange in matrices, the transpose operator’ (quote) is applied, for example:

u02-23-9780857094872

2.2.2 Matrix operations

Vectors, matrix, and arrays can be used in various mathematical operations in the same way as single variables, as illustrated below.

Addition and subtraction

Addition and subtraction of two matrices are performed element by element, provided the matrices are equal in size, e.g. when A and B are two matrices sized 3 × 2 each:

A=[A11A12A21A22A31A32]andB=[B11B12B21B22B31B32]

si15_e

The sum of these matrices is

[A11+B11A12+B12A21+B12A22+B22A31+B31A32+B32]

si16_e

In addition and subtraction operations the commutative law is valid, namely A + B = B + A.

Multiplication

Multiplication of matrices is more complicated. In accordance with the rules of linear algebra, it is feasible only when the number of row elements in the first matrix equals that of column elements in the second matrix, or, in other words - the inner dimensions of the matrices must be equal. Thus, the above matrices A, 3 × 2, and B, 3 × 2, cannot be multiplied, but if B is replaced by another, sized 2 × 3,

B=[B11B12B13B21B22B23]

si17_e

the inner dimensions of the matrices are equal and multiplication becomes possible.

[A11B11+A12B21A11B12+A12B22A11B13+A12B23A21B11+A22B21A21B12+A22B22A21B13+A22B23A31B11+A32B21A31B12+A32B22A31B11+A32B23]

si18_e

It is not difficult to verify that the product B*A is not the same as A*B, the commutative law does not apply here.

Various examples of matrix addition, subtraction and multiplication are given below

u02-24-9780857094872
u02-24a-9780857094872

An important advantage of matrix multiplication is the possibility to present a set of linear equations in matrix form. For example, the set of two equations with two variables

A11x1+A12x2=B1A21x1+A22x2=B2

si19_e

may be written in compact matrix form as AX = B or in full matrix form as

[A11A12A21A22][x1x2]=[B1B2]

si20_e

Division

Division of matrices is even more complicated than their multiplication because of the above-mentioned non-commutative properties of the matrix. A full explanation can be found in books on linear algebra. Here, the related operators are described in the context of their use in MATLAB®.

Identity and inverse matrices are often used in dividing operators. An identity matrix I is a square matrix whose diagonal elements are 1s and whose others are 0s. It can be generated with the eye command (see Table 2.4). The commutative law applies for the multiplication of the square matrix A by I, or I by A, and yields the same result: AI = IA = A.

Table 2.4

Command for matrix manipulations, generation and analysis; dates and their conversion

Form of MATLAB® presentationDescriptionMATLAB® example (inputs and outputs)
length(x)Returns the length of vector x.>> x = [3 7 1];
>>length(x)
ans = 3
size(a)Returns a two-element row vector; the first element is the number of rows in matrix a and the second, the number of columns.>>a = [1 2; 7 3; 9 6];
>>size(a)
ans = 3 2
reshape(a,m,n)Returns an m-by-n matrix whose elements are taken column-wise from a. Matrix a must have m*n elements.>>reshape(a,2,3)
ans =
1 9 3
7 2 6
repmat(a,m,n)Generates the large matrix containing m × n copies of a.>>a = [0 1;1 0];
>>b = repmat(A,1,2)
b =
0 1 0 1
1 0 1 0
strvcat(t1,t2,t3,. . .)Generates the matrix containing the text strings t1, t2, t3, . . . as rows.>> t1 = ‘Alanine’;
>> t2 = ‘Arginine’;
>> t3 = ‘Asparagine’;
>> strvcat(t1,t2,t3)
ans =
Alanine
Arginine
Asparagine
zeros(m,n)Generates an m by n matrix composed of zeros.>> zeros(2,3)
ans =
0 0 0
0 0 0
diag(x)Generates a matrix with elements of vector x placed diagonally.>> x = 1:3;diag(x)
ans =
1 0 0
0 2 0
0 0 3
eye(n)Generates a square matrix with diagonal elements 1 and others 0.>> eye(4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
randi(imax,m,n)Returns an m by n matrix of integer random numbers from value 1 up to imax– maximal integer value.>> randi(10,1,3)
ans =
9 10 2
min(a)Returns a row vector with minimal numbers of each column in the matrix a. If a is vector, returns the minimal number in a.>> a = [1 2; 7 3; 9 6];
>> b = min(a)
b =
1 2
>> a = [1 2 7 3 9 6];
>> b = min(a)
b =
1
max(a)Analogous to min but for maximal element.>> a = [1 2 7 3 9 6];
>> b = max(a)
b =
9
mean(a)Returns a row vector with arithmetical mean values calculated for each column of the matrix a. If a is a vector, returns the average value of the vector a.>> a = [1 2; 7 3; 9 6];
>> b = mean(a)
b =
5.6667 3.6667
median(a)Returns a row vector with median values (central values of ordered data in a) for each column of the matrix a. If a is a vector, returns the average value of the vector a.>>a = [1 2; 7 3; 9 6];
>>b = median(a)
b =
7 3
sum(a)Returns a row vector with column sums of matrix a. If a is a vector, returns the average value of vector a.>> a = [1 2; 7 3; 9 6];
>> sum(a)
ans =
17 11
cumsum(a)Returns cumulative sums over each column of the matrix a.>> X = [1 2 3;4 5 6];
>> cumsum(X)
ans =
1 2 3
5 7 9
std(a)Analogous to sum but calculates standard deviation. [1n1ni=1(aiμ)2]12,si3_e with μ as a mean of n elements for each column of a.>> a = [1 2; 7 3; 9 6];
>> std(a)
ans =
4.1633 2.0817
det(a)Calculates the determinant of the square matrix a.>> a = [5 6;12 1];
>> det(a)
ans =
-67
[y,ind] = sort(a,dim,mode)For vector or matrix. Sorts elements of a in the dim dimension: 1 – along columns and 2 – along rows and in ‘ascend’ or ‘descend’ mode order. Returns ordered y and indices of the a for each y.>> a = [5 6;12 1;7 1];
>>
[y,ind] = sort(a,2,‘descend’)
y =
6 5
12 1
7 1
ind =
2 1
1 2
1 2
num2str(a)Converts single number or numerical matrix elements into a string representation.>> a = 12.4356;
>> num2str(a)
ans
=12.4356
dateGenerates a string with the current date in dd-mmm-yyyy format.>> date
ans =
27-Mar–2013
datenum(d)Converts the string d with the date and time to serial date numbers.>> datenum(‘27-Mar–2013’)
ans =
735320
datestr(num)Converts serial date numbers num to the date strings.>> datestr(735320)
ans =
27-Mar–2013
addtodate(D, Q, F)Adds Q to scalar serial date number D; F should be written as ‘day’, or ‘month’, or ‘year’.>> t = addtodate(735320, − 7, ‘day’);
>>datestr(t)
ans
=20-Mar–2013

t0025_at0025_b

Matrix B is called the inverse of A when left or right multiplication leads to the identity matrix: AB = BA = I. The inverse matrix can be written as A− 1. In MATLAB®, this can be written in two ways: B = A^-1 or with the inv command as B = inv(A).

Where matrix products are involved, left, , or right, /, division is used. For example, to solve the matrix equation AX = B, when A is a square matrix and X and B are column vectors, left division should be used: X = AB. Whereas to solve XC = B, with X and B row vectors and C as a transposed matrix of A, right division should be used: X = B/C.

Use matrix division to solve the following set of equations.

x12x2=86x1+8x2=12

si21_e

Based on the explanations above, this set of equations can also be rewritten in another form with coefficients to the right of unknowns x1 and x2 as

x1x22=8x16+x28=12

si22_e

These two possible representations correspond to the two matrix forms:

AX=BWithA=[1268],B=[812],andX=[x1x2]

si23_e

or

XC=DWithC=[1628],D=[812],andX=[x1x2]

si24_e

The commands for solutions for the two forms discussed are:

u02-25-9780857094872

An application example with matrix division is given in Subsection 2.3.4.1.

2.2.3 Array operations

All previously described operations concern matrices obeying linear algebra rules; however, there are many calculations (in particular in QA science), where the operations are carried out by the so-called element- by-element procedure. In these cases, to avoid confusion, we use for them the term ‘array’. These element-wise operations are carried out with elements in identical positions in the arrays. In contrast to matrix operations, element-wise operations are confined to arrays of equal size; they are denoted with a point typed preceding the arithmetic operator, namely:

.*(elementwisemultiplication);./(elementwiserightdivision);.(elementwiseleftdivision);.^(elementwiseexponentiation).

si25_e

For example, if we have vectors a = [a1 a2 a3] and b = [b1 b2 b3] then element-by-element multiplication a.*b, division a./b, and exponentiation a.^b yields:

a.*b=[a1b1a2b2a3b3],a./b=[a1/b1a2/b2a3/b3],anda.b=[ab11ab22ab33]

si26_e

The same manipulations applied for two matrices

A=[A11A12A13A21A22A23]

si27_e

and

B=[B11B12B13B21B22B23]

si28_e

leads to:

A.*B=[A11B11A12B12A13B13A21B21A22B22A23B23],A./B=[A11/B11A12/B12A13/B13A21/B21A22/B22A23/B23],

si29_e

and

A.^B=[B11B12B13A11A12A13B21B22B23A21A22A23]

si30_e

Element-wise operators are frequently used for calculating a function at series of values of its argument. Examples of array operations are:

u02-26-9780857094872
u02-26a-9780857094872

2.2.4 Some special matrices and commands for their ģeneration

Matrices with some certain or random values can be generated with special commands. The

ones(m,n)andzeros(m,n)

si31_e

commands are used for matrices of m rows and n columns with 1 and 0 as all elements.

Many engineering problems related to descriptive statistics, process quality and various simulations involve random numbers, for which the following generators of pseudorandom numbers should be used:

rand(m,n)orrandn(m,n):

si32_e

the former command yielding a uniform distribution of elements between 0 and 1 and the latter a normal one with mean 0 and standard deviation 1. For generating a square matrix (n × n), these commands can be abbreviated to rand(n) and randn(n). Examples are:

u02-27-9780857094872
u02-27a-9780857094872

Integer random numbers can be generated with the randi command as shown in Table 2.4.

Note: when we repeatedly use the rand, randn, or randi command, the new random numbers are generated each time; to restore the settings of the random number generator to produce the same random numbers as if you had restarted MATLAB®, the rng default command should be typed and entered into the Command Window. To repeat the generated random numbers, the start settings should be previously retrieved with the rng command, for example:

u02-28-9780857094872
u02-28a-9780857094872

Additional random number generators are available for producing values from other statistical distributions, and are described in Chapter 4.

In addition to the commands described in the previous sections, MATLAB® has many others that can be used for manipulation, generation and analysis of matrices and arrays; some of these are listed in Table 2.4.

All matrices described above, except for some of those in Table 2.4, have numerical elements, even if they are written as expressions, as these expressions yield numbers, when evaluated. However, as a single element or number of elements of a matrix, a string/s can be used. A string is an array of characters - letters and/or symbols. A string is entered in MATLAB® between single quotes, e.g.,

u02-29-9780857094872

Each character of the string is presented and stored as a number (thus the set of characters represents a vector or an array) and can be addressed as an element of a vector or array, e.g., S(5) in the string ‘Reliability’ is the letter ‘a’. Some examples with string manipulations are:

u02-30-9780857094872

Strings can be placed as elements in a vector or a matrix. String rows are divided by a semicolon (;) just as numerical rows and strings within the rows are divided by a space or a comma. Rows should have the same number of elements and each column element must be the same length as the longest of the rows. To achieve this alignment, spaces should be added to shorter strings; for example,

u02-31-9780857094872

Calculating the number of spaces to add to each string in the column is a tedious procedure for the user; to avoid this, use the strvcat (will be removed in new MATLAB versions, use char (t1, t2, t3 . . .) instead) command, as shown in Table 2.4.

2.2.5 How to output a table with the disp and fprintf commands

The disp and fprintf commands can display vectors, matrices and a caption (see Subsection 2.1.7). Thus, these commands can be used for output data in tabular form.

Let us show first how it can be done with the disp command. For example, bearing ball diameter data with captions as per Table 2.3 should be displayed using the following commands:

u02-32-9780857094872

Use now the fprintf command. This command permits a formatted output, for example the same A-matrix with numbers displayed with one decimal digit can be presented as a table with the following commands:

u02-33-9780857094872

The fprintf command prints rows as columns; for this the 4 x 3 A matrix was transposed to the 3 x 4 A’ matrix and the format for output was written for three columns; to display each table row on the new line the (back slash and letter n without space) signs should be written at the end of the column format.

2.2.6 Application examples

2.2.6.1 Table of statistical measures

In many quality-assurance calculations the following statistical measures are used: mean, median, mode, range and standard deviation.

Problem: Generate and display the matrix in which the first column is the serial number and the second is the statistical measure name.

Execute using the following steps:

 Generate a numerical column of values from 1 to 5.

 Generate a string column with the names Mean, Median, Mode, Range, and Standard deviation.

 Join these two columns in to a matrix. In MATLAB, all matrix elements should be of the same type, e.g., if strings are written in one column, then another column must also contain strings or vice-versa; in our case, we use the num2str command, which transforms numerical data into strings.

 Display the table title ‘Statistical measures’.

 Display a two-column matrix with serial numbers and measure names.

The commands are:

u02-34-9780857094872

2.2.6.2 Population statistics

In a laboratory, the bacterial cell population in two batches was tested at different times and presented in two rows (batches) and ten columns (times) as follows

27 35 28 32 33 31 35 28 30 32 35 34 33 36 35 31 27 28 35

Problem: Find the mean (arithmetic), median (central value of ordered set), range (difference between maximal and minimal values) and the standard deviation (see Table 2.4) for every row of data, and display the mean, median, and range values as integer numbers, and the resulting standard deviation with two decimal places, using the fprintf command.

The steps are as follows:

 The bacterial growth data are assigned to a two-row matrix;

 The mean, median, range and standard deviation are calculated for every row data by the appropriate MATLAB® commands;

 The obtained statistics are displayed using the fprintf command; the mean values and range are shown as fixed numbers without decimal digits, and those of the standard deviation as fixed numbers with two decimal digits.

The commands are:

u02-35-9780857094872

2.2.6.3 MTTF - mean time to failures

The mean time to failures, MTTF, of a semiconductor circuit due to movement of ions can be calculated by the Black’s equation

MTTF=AjneEakT

si33_e

where Ea is the activation energy, T is operating temperature, k is the Boltzmann constant, j is current density, A is a coefficient, and n is the dimensionless power.

Problem: Write the commands for obtaining the matrix MTTF by giving vectors j and T. Output a table arranged so that the rows are presented MTTF at constant j and the columns at constant T. Use the following parameters: Ea = 1.1 eV, k = 8.6173 4 10− 5 eV/K, n = 2 dimensionless, A = 2.19.10− 14 hour (cm2/A)n, j is given from 1.65 to 1.8 in steps of 0.05 A/cm2, and T is 293.15, 298.15, 300, 302, and 305 K.

The steps are as follows:

 Generate the column-vector j (size 4 x 1) and the row-vector T (size 1 x 5) separately;

 Calculate the MTTF-matrix according to the formula. The first multiplier of the MTTF expression (after element-wise exponentiation and division, A/jn) has the size 4x1, and the second (after element-wise division on T and exponentiation, eEakTsi34_e), the size 1x5; thus, their product according to the linear algebra rule would be the size 4 x 5 (the extreme values of the sizes of these vectors).

 Display the title ‘Mean time to failure’ and the MTTF-matrix with the digits before the decimal point only.

The commands for the solution are:

u02-36-9780857094872
u02-36a-9780857094872

2.2.6.4 Weight versus height

Measurements of students’ weight w (in cm) and height h (in kg) in a group at an American college showed the following results: heights - 155, 175, 173, 175, 173, 162, 173, 188, 190, 173, 173, 185, 178, 168, 162, 185, 170, 180, 175, 180, 175, 175, 180, and 165; weights - 54, 66, 66, 71, 68, 53, 61, 86, 92, 57, 59, 80, 70, 59, 50, 145, 68, 78, 67, 90, 75, 74, 84, and 53. These data were fitted with the regression line

wfit = 906.14 - 11.39h + 0.03780h2

The upper and lower values of the confidence band (also called Working-Hotelling confidence band) of the regression line can be evaluated as:

wlower,upper=wfit±2Fni=1(wi-wfiti)2n-2[1n+(hi-h)2ni=1(hi-h)2]

si60_e

where ‘+’ for upper and ‘−’ for low confidence values; n = number of students, ˉhsi35_e is a mean value of the height, F denotes the F-distribution value which is 3.443 for the studied case: n = 24 and a = 0.05.

Problem: Write the commands to input data in a two-row matrix, w_h, and calculate: the weight by the expression, the percentage error, 100 (w-wfit)/w, and the lower and upper values of the confidence band. Display the results as a five-column table listing every third value of the w, wf, error, low and upper bonds.

The steps are as follows:

 Assign the F, the height and weight values, as above.

 Calculate the weights wfit, percentage errors, and confidence band using the above expressions.

 Write every third value of the inputted and calculated values of weight, calculated errors and confidence bands in a five-row matrix tab and display as a five-column table.

u02-37-9780857094872

2.3 Flow control

A calculation program represents a sequence of commands implemented in a given order. However, there are many cases when the written order of single, or group, commands should be altered, for example, when a calculation should be repeated with new parameters, or when one expression out of several is chosen to calculate a variable. For instance, analyzed data were fitted by two different expressions, each of which is accurate in a different area within the data. In this case, the area should be checked to use the correct computing expression. In other situations, in calculations with the given tolerance of the answer, it may be necessary to repeat commands several times until the error in the answer diminishes to a size that is smaller than required. To realize these processes, flow control is applied. In MATLAB®, special commands, usually called conditional statements, are used for these purposes; these commands direct the computer to choose which command should be carried out next. The most frequent flow control commands are described below.

2.3.1 Relational and logical operators

Important operations in flow control are realized using relational and logical commands. Both groups of commands test the similarity between pairs of values or statements, but the first operates mostly with numerical values while the second, with Boolean values.

Relational operators

Operators matching a pair of values are called relational or comparison operators; the application result of such an operator is written as 1 (true value) or 0 (false value), e.g., the expression x<3 results in 1 if x is less than 3, and in 0 if otherwise. The relational operators are:

< (less than),

> (greater than),

< = (less than or equal to),

> = (greater than or equal to),

= = (equal to),

~ = (not equal to).

Note: two-sign operators should be written without spaces.

When a relational operator is applied to a matrix or an array, it performs element-by-element comparisons. The comparisons return the array of 1s, where the relation is true (the array has the same size as the size of compared matrix), and 0s, where it is not. If one of the compared objects is scalar and the other is a matrix, the scalar is matched against every element of the matrix. The ones and zeros are logical data, which is not the same as numerical data, although they can be used in arithmetical operations.

Some examples are:

u02-38-9780857094872
Logical operators

Logical operators are designed for operations with the true or false values within the logical expressions. They can be used as addresses in another vector, matrix or array; see, for instance, the last three example commands.

In MATLAB®, there are three logical operators: & (logical AND), | (logical OR), and ~ (logical NOT). Like the relational operators, they can be used as arithmetical operators and with scalars, matrices and arrays. Comparison is element-by-element with logical 1 or 0 accordingly as the result is true or false respectively. MATLAB® also has equivalent logical functions: and(A,B) equivalent to A&B, or(A,B) - to A|B, not(A,B) - to A~B. If the logical operators are performed on logical variables, the results are according to the rules of Boolean algebra. In operations with logical and/ or numerical variables, the results are logical 1 or 0.

Some examples are:

u02-39-9780857094872

Among the MATLAB® logical functions is find, which in its simplest forms reads as

i=find(x) or i=find(A>c)

where i is a vector of the place addresses (indices), where non-zero elements of the x (first form) are located, or are elements of A larger than c (second form; in this case, any of the relational operators can also be used, e.g., <, > = , etc.); for example, vector T = [11 8.5 5.5 0–1.5], thus

>> i = find(T)

i =

1 2 3 5

>> i = find(T<6)

i =

3 4 5

The order in which combinations of relational, logical and conditional operators is executed (so-called precedence rules) are available in advanced MATLAB® courses. The order of execution necessary for such an operator can also be reached using parentheses.

2.3.1.1 Application example: outlying results

Test results for the current strength CS of 15 measurements are: 10.3, 10.4, 9.6, 10.4, 10.1, 9.6, 9.8, 14.9, 10.1, 5.4, 10.5, 10.5, 10.0, 10.3 and 10.5 mA. There are two measurements that are sharply different from the rest (namely, 14.9, 5.4). Should these data be discarded to carry out correct data analysis? The following criteria can be used for this purpose:

|CSiu|σ>tq

si36_e

then the CSi can be discarded. In this expression μ and σ are the mean and standard deviation respectively, tq is the critical value of 2.409 for our case (15 values, and a supposed significant level 5%).

Problem: Use the above relational and logical operators to form two vectors of weight (a) without outliers, (b) outliers. Display results with the ‘Normal CS, mA’, ‘Outliers, mA’ captions.

The steps are as follows:

 Assign the weight values as above.

 Calculate the data number n, the mean average and the standard deviation sigm.

 Identify the locations of the outlying values using the abs(CS-mu)/ sigm>tq logical command, and save in the out_logic logical vector with 1s and 0s in the places of the outlying and normal CS values respectively.

 Assign the outliers vector with the addresses of the outlying values using the find command, with the out_logic vector used in this case as a vector with outliers addresses.

 Two vectors, comprising weights without outliers, and outliers, are formed and displayed.

The commands used to solve this problem are:

u02-40-9780857094872

2.3.2 The If statements

Flow control commands are used to manage the order of the execution of commands. This order is provided by various conditional statements. The first is the if statement, which has three forms: if . . . end, if . . . else . . . end, and if . . . elseif . . . else . . . end. Each if construction should terminate with the word end; its words appear on the screen in blue. The if statement forms and their constructions are shown in Table 2.5:

Table 2.5

The If statement forms

The formThat is how commands should be designed
if . . . endif conditional expression
MATLAB® command/s
end
if . . . else . . . endif conditional expression
MATLAB® command/s
else
MATLAB® command/s
end
if . . . elseif . . . else . . . endif conditional expression
MATLAB® command/s
elseif conditional expression
MATLAB’ command/s
else
MATLAB’ command/s
end

In this table, the conditional expression uses the relational and/or logical operators, for example a < = v1&a > = v2 or b ~ = c.

When the if conditional statement is typed and entered in the Command window next to the prompt >>, the new line (and additional lines, after pressing enter) appears without the prompt until the word end is typed and entered.

An application example with the if statement is presented at the end of Subsection 2.3.4.2.

2.3.3 Loops in MATLAB®

A loop is another method of program flow control; it permits a single command, or a group of commands, to be repeated several times. Each cycle of commands is termed a pass. There are two loop commands in MATLAB®: for . . . end and while . . . end. These words appear on the screen in blue. Similar to the if statement, each for or while construction should terminate with the word end.

The loop statements are written in a general form in Table 2.6.

Table 2.6

Loops

for . . . end loopwhile . . . end loop
for k=[initial : step : final]
MATLAB’ command/s
end
while conditional expression
MATLAB’ command/s
end

In for . . . end loops, the commands written between for and end are repeated k times, a number which increases in every pass by the addition of the step-value; this process continues until k reaches or exceeds the final value.

The square brackets in the expression for k (Table 2.6) mean that k can be assigned as a vector, for example k = [3.5 − 1.06 1:2:6]. The brackets can be omitted if there are only colons in k, e.g., k = 1:3:10. The last pass is followed by the command next to the loop. For some calculations realized with for . . . end loops, matrix operations can also be used. In such cases, the latter are actually superior, as the for . . . end loops work slowly. The advantage is negligible for short loops with a small number of commands, but appreciable for large loops with numerous commands.

The while . . . end loop is used where the number of passes is not known in advance and the loop terminates only when the conditional expression is false. MATLAB® executes the commands written between the while and end in each pass; the passes are repeated until the conditional expression is true. An incorrectly written loop may continue indefinitely, for example:

>>a = 2;

>>while a > 0

a = 1.5*a

end

In this case, after a becomes greater than 1.7977.10308 (the maximum possible positive real number), the expression a = inf appears repeatedly on the screen. To interrupt the loop, the Ctrl and C keys should be pressed simultaneously.

Examples of for . . . end and while . . . end loops used for calculating exponential e-x (which is present in many distributions used for evaluating quality) via the series nk=0(1)kxkk!si37_e at x=pi/6, are:

u02-41-9780857094872

In the first example, the term sum s is calculated in the for . . . end loop. At the beginning of the first pass, the s value is equal to zero; during this pass, the first term (k = 0) is calculated and added to the s. In the second pass, k = k+1 = 1, the second term of the series is calculated and added to the previous s value. This procedure is repeated in this example up to k = n, n = 5. After this, the loop ends and the obtained value is displayed by typing and entering the variable names. In the case of the for . . . end loop, the number of passes is fixed.

The second example for the while . . . end loop presents a more complicated situation. In this case, a condition for ending the loop should be given - here, the value of the kth term, larger than 0.0001, is used. As in the previous case, in the first pass, the s value is equal to zero and k = 0 (k in this case is called counter); these values are assigned before the loop. In this pass, the first term of the series is calculated and added to the sum s; then the k value is increased by 1. The new term (without a sign) is calculated and checked if it is greater than 0.0001. If this condition is true, the next pass is started for the next term calculation, and if it is false - the loop ends and the fprintf command displays the obtained s value and the number of times the term was used; as the latter value is an integer, then the conversion character i is used for displaying the value of k.

Note: the for . . . end and while . . . end loops and if statements can incorporate additional loops and/or if-statements; the order and number of these inclusions is not restricted and is predetermined only by calculation purposes.

2.3.4 Application examples

2.3.4.1 Linear regression: defining of the coefficients

Regression analysis is widely used in the QA sciences to describe possible relationships between the dependent y and independent x variables. For example, an experiment shows the following data - y = 2, 7, 11, 18, and 23 at x = 0.8, 2.1, 4, 4.9, and 5.7 respectively. These data can be described by the linear regression y = a1+a2xsi38_e in which the coefficients a1 and a2 are obtained from the following set of equations

a1n+a2ni=1xi=ni=1yia1ni=1xi+a2ni=1x2i=ni=1yixi

si39_e

where n is the number of the observed values.

This set can be represented in the matrix forms AX = B or XA = B, in our case:

[nni=1xini=1xini=1x2i][a1a1]=[ni=1yini=1yixi]or[a1a1][nni=1xini=1xini=1x2i]=[ni=1yini=1yixi]

si40_e

Problem: Define the a-coefficients with left- and right-division; print the result as a linear equation with the relevant coefficients a1 and a2.

The steps to be taken are as follows:

 Generate two-row vectors with the given y and x values.

 Generate a 2 x 2 matrix A with the sums on the left-hand side of the first matrix forms; the sum command can be used for sums.

 Generate a column vector B with the sums on the right-hand side of the first matrix equation.

 Use left division AB to calculate the a-coefficients.

 Display the coefficients in the written linear equation using the fprintf command.

 Use right-hand division for A/B. Write A as per the second matrix equation, using the quote operator (’). The letter is used to transform the column vector B into the row vector; the right division in this case is simply a verification of the previous solution.

 Display the coefficients directly in the written linear equation using the fprintf command.

The commands for the solution are:

u02-42-9780857094872

2.3.4.2 Triangular distribution: PDF - probability density function

When data is presented by the lower a and higher b limits, and by the most likely value c, a triangular distribution is typically used in various QA simulations. The PDF of this distribution is:

PDF={0,x<aorx>b2(xa)(ba)(bc),axc2(bx)(ba)(bc),c<xb

si41_e

where x is independent random variable.

Problem: Calculate CDF at a = 20.3, b = 24.1, c = 22, and x = 20, a, 20.5, 21, 21.5. . ., 24, b and 24.5.

The steps required:

 Determine the variables a, b and c, and a 1 x 12 vector with the x values.

 Use the for . . . end loop in which every pass runs the new x value defined by its index (address) - x(i).

 Introduce into the loop the statement if . . . elseif . . . else . . . end, where the conditions and expressions on the right-hand side of the PDF equation are written in the blank spaces. The PDF values should be indexed in order to generate the vector of these values for each x.

 Display the vector of calculated PDF values with fprintf.

The commands for calculating N are

u02-43-9780857094872

2.3.4.3 Felt air temperature

A quantitative measure called felt air temperature or wind chill index represents the amount of heat that the human body loses. It can be calculated by standard engineering correlations between wind speed v and air temperature T. In the United States, the expression used is:

w = v°’16(0.4275T - 35.75) + 0.6215T + 35.74

where w is in degrees Fahrenheit, v is in mph (rises from 10 to 60 in steps of 10) and T decreases from 40° to − 40° with step 20°,3 also in Fahrenheit.

Problem: Write the command for the wind chill matrix, giving vectors v and T; display it as a table, so that w is arranged in the rows at constant v and in the columns at constant T.

There are two ways to carry out the command - without loops, using the vectors for v and T only, and using the for . . . end loops. The steps are as follows:

 Generate separately the column-vector v (size 5 x 1) and the row-vector T (size 1 x 5).

 Calculate the w-matrix according to the formula. The first multiplier of the w-expression, v0.16 (after element-wise exponentiation of v) has the size 5 x 1, and the second multiplier (the terms in the parentheses), the size 1 x 5; thus, according to linear algebra, their product would be the size 5 x 5 (the extreme values of the sizes of these vectors). The sum of 0.6215T and 35.74 on the right-hand side of the w-equation represents a column vector of the size 5 x 1, and cannot be summed with the initially-defined matrix, which is of the size 5 x 5 (according to the rules of matrix addition, the matrices must be equal in size). Thus, this column vector should be repeated 5 times (the number of columns in the matrix). This can be done with multiplication using the ones(size(v)) terms.

 Display the title ‘Wind chill’ and the w-matrix with the digits preceding the decimal point only.

 Repeat the same calculations, using for . . . end loops; for this, it is necessary to calculate w (with the expression above) in the two for . . . end loops: the external loop for v and the internal loop - for T; such a construction yields all values v for each v,T-pair.

 Display again the title ‘Wind chill’ and the w-matrix with the digits preceding the decimal point only.

The commands used for the solution are:

u02-44-9780857094872

2.4 Questions for self-checking

Display values of the calculated wind chill indices using fprintf.

1. The following command should be used to list the variables in the current workspace together with their byte size and other information: (a) lookfor, (b) whos, (c) who?

2. In the shortE format, the predefined variable π is displayed as: (a) 3.1416, (b) 3.14, (c) 3.1416e+000, (d) 3.141592653589793, (e) 3.141592653589793e+000?

3. In MATLAB® form, the y=In2.303log10si42_e expression should be written as follows: (a) y = ln(2.303)/log(10), (b) y = ln(2.303)/log(10), (c) y = log(2.303)/log10(10), (d) y = log(2.303)/log(10)?

4. The V = [1 2;3 4] command produces: (a) a row vector V with four numbers; (b) a column vector V with four numbers; (c) a square matrix V with four numbers?

5. The matrix [100010001]si43_e can be generated with: (a) diag(1:3), (b)eye(3), (c) ones(3), (d) zeros(3,4)?

6. Normally, distributed random numbers can be generated with the following command: (a) randi, (b) randn, (c)rand?

7. Check which of the answers below provide the correct result for [3 6;9 12]/[1 2;3 4] division:

(a) ans =(b) ans =
3 33 0
3 30 3


8. A row vector E of numerical values can be transformed into a column vector with the following MATLAB® expression: (a) E− 1, (b) inv(E),(c) 1/E, (d) E’?

9. An element located in the second row and the third column of the 4 x 4 matrix A should be addressed by the following MATLAB® expression: (a) A(3,2), (b) A(10), A(32), (c) A(6), (d) A(2,3)?

Note: There may be more than one correct answer.

2.5 Answers to selected questions

2. (c) 3.1416e+000

3. (c) y = log(2.303)/log10(10)

6. (b) randn

8. (d) E’


1 Text, screenshots, and tables used in this subsection are partly taken from pages 2–11, and 13 of the author’s book MATLAB® in Bioscience and Biotechnology, Biohealthcare Publishing (Oxford) Limited, Oxford-NY, 2011.

2 The background color changed.

3 The ranges and steps are taken arbitrarily and differ from those usually used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.92.209