135
Your self-paced MATLAB training... What is MATLAB? The word MATLAB stands for MATrix-LABoratory. This virtual lab is a program for high-performance numerical operations and visualization. It provides an interactive environment with a lot of built-in commands and functions for numerical analysis and graphics, and also provides easy extensibility with its own high- level programming language. There are numerous prepared commands for 2D and 3D graphics as well as for animation. The user is not limited to the built-in functions; he can write his own functions in MATLAB language. Once written, these functions work just like the internal functions. MATLAB's language is designed to be easy to learn and use. The many built-in functions provide excellent tools for linear algebra, signal processing, data analysis, optimization, solution of ordinary differential equations (ODEs), and many other types of scientific operations. There are also several optional 'toolboxes' available which are collections of functions written for special applications such as 'Image Processing', 'Statistics', 'Neural Networks', etc. The basic building block in MATLAB is the matrix. The fundamental data type is the array. Vectors, scalars, real and complex matrices are all automatically handled as special cases of basic arrays. The built-in functions are optimized for vector operations. Thus, vectorized commands or codes run much faster in MATLAB (vectorization is a way of computing in which an operation is performed simultaneously on a list of numbers rather than sequentially on each member of the list).

Matlab Exer

Embed Size (px)

Citation preview

Page 1: Matlab Exer

Your self-paced MATLAB training...What is MATLAB?

The word MATLAB stands for MATrix-LABoratory. This virtual lab is a program for high-performance numerical operations and visualization. It provides an interactive environment with a lot of built-in commands and functions for numerical analysis and graphics, and also provides easy extensibility with its own high-level programming language.

There are numerous prepared commands for 2D and 3D graphics as well as for animation. The user is not limited to the built-in functions; he can write his own functions in MATLAB language. Once written, these functions work just like the internal functions. MATLAB's language is designed to be easy to learn and use.

The many built-in functions provide excellent tools for linear algebra, signal processing, data analysis, optimization, solution of ordinary differential equations (ODEs), and many other types of scientific operations.

There are also several optional 'toolboxes' available which are collections of functions written for special applications such as 'Image Processing', 'Statistics', 'Neural Networks', etc.

The basic building block in MATLAB is the matrix. The fundamental data type is the array. Vectors, scalars, real and complex matrices are all automatically handled as special cases of basic arrays. The built-in functions are optimized for vector operations. Thus, vectorized commands or codes run much faster in MATLAB (vectorization is a way of computing in which an operation is performed simultaneously on a list of numbers rather than sequentially on each member of the list).

A nice thing to realize is that MATLAB is primarily a numerical computation package, although with the 'Symbolic' Toolbox it can do also symbolic algebra. Mathematica, Maple, and Macsyma are primarily symbolic algebra packages. MATLAB's ease of use is its best feature since you can have more learning with less effort, while the computer algebra systems have a steeper learning curve.

In mathematical computations, especially those that utilize vectors and matrices, MATLAB is better in terms of ease of use, availability of built-in functions, ease of programming, and speed. MATLAB's popularity today has forced such packages as Macsyma and Mathematica to provide extensions for files in MATLAB's format.

Basic MATLAB helpIn this section we talk about some very basic features and commands. This is a type of Matlab help. To begin with, we look at the general structure of the environment.

Page 2: Matlab Exer

Typing 'help function' (in the Matlab command window), with the appropriate function or command name, provides detailed help for any of the functions or commands available. We encourage the use of the online Matlab help.

Command windowThis is the main window. It is characterized by the MATLAB command prompt '>>'. When you launch the application, MATLAB puts you in this window. All commands are typed here, at the MATLAB prompt.

Command HistoryAll commands typed on the MATLAB prompt in the command window get recorded, even across multiple sessions. You can select a command from this window with the mouse and execute it in the command window by double clicking on it. You can also select a set of commands from this window and create an m-file with the right click of the mouse, and also selecting the appropriate option from the menu.

WorkspaceThis subwindow lists all variables that you have generated so far and shows their type and size. You can do various things with these variables by clicking on a variable and then using the right button on the mouse to select your option.

Current DirectoryThis is where all your files from the current directory are found. You can do file navigation here. You also have several options of what you can do with a file once you select it. To see the options, click the right button of the mouse after selecting a file. You can run m-files, rename them, delete them, etc.

Edit windowThis is where you write or edit and save your own programs in files called 'M-files'. You can use any text

Page 3: Matlab Exer

editor to carry out these tasks. MATLAB provides its own built-in editor. However, you can use your own editor by typing the standard file-editing command that you normally use on your system.

Graphics windowThe output of all graphics commands typed in the command window are flushed to the Graphics or Figure window, a separate window with white background color.

DemoThe MATLAB help has a demo facility to show many of its features. The program includes a tutorial introduction that is worth trying. Type 'demo' at the MATLAB prompt to invoke the demonstrations, and follow the instructions.

On-line documentationThe MATLAB help provides on-line examples for all its built-in functions and programming language commands. You can get Matlab help just typing 'help function' on your command window. You'll see fast-helpful examples.

Input-OutputMATLAB supports interactive computation, taking the input from the screen, and flushing the output to the screen. Additionally, it can read input files and write output files.

Data typesThe fundamental data type in MATLAB is the array.It includes several distinct data objects: integers, real numbers, matrices, strings, structures, and cells. In most cases you never worry about the data type or object declarations. MATLAB automatically sets its variables to match what you need.

Page 4: Matlab Exer

DimensioningDimensioning is automatic in MATLAB. No dimension statements are required for vectors or arrays. You can find the dimensions of an existing matrix or a vector with the 'size' and 'length' commands.

Case sensitivityMATLAB is case-sensitive; that is, it differentiates between the lowercase and uppercase letters. Thus 'm' and 'M' are different variables. MATLAB commands and function are typed in lowercase letters.

Output displayThe output of every command is displayed on the screen unless MATLAB is directed otherwise. A semicolon at the end of a command suppresses the screen output, except for graphics.

Output formatComputations inside MATLAB are performed using double precision, but the appearance of floating point numbers on the screen is controlled by the 'format' in use. There are several different output formats. The following list shows the 'pi' value in several formats:

format short 3.1416format long 3.14159265358979format hex 400921fb54442d18format short e 3.1416e+000

The formats 'format compact' and 'format loose' control the spacing above and below the displayed lines. The default is format short.

Command historyMATLAB saves previously typed commands in a buffer. These commands can be recalled with the up-arrow key (this helps in editing previous commands). You can also copy and paste commands from the 'Command History' subwindow where all your commands from even previous sessions of MATLAB are recorded and listed.

File typesM-files are standard ASCII text files, with a '.m' extension. There are two types of these: script files and function files. Most of the programs that you write in MATLAB are saved as M-files. All built-in functions are M-files, most of which reside on your computer in a special format.

Mat-files are binary data-files, with a '.mat' extension to the filename. Matfiles are created by MATLAB when you save data with the 'save' command. The data is written in a special format that only MATLAB can read. These files can be loaded into MATLAB with the 'load' command.

Mex-files are MATLAB-callable Fortran and C programs, with a '.mex' extension to the filename.

Page 5: Matlab Exer

Creating a directory and saving filesIn MATLAB, there's a default folder called 'work' where MATLAB saves your files if you do not specify any other location. However, it is better if you create a separate folder for saving your work. If you need to store your files somewhere else, you might have to specify the path to the files using the 'path' command, or change the working directory of MATLAB to the desired directory with the 'cd' command.

PrintingOn PCs, you can print the contents of your current active window (command, figure, or edit window), select Print... from the File menu and click Print in the dialog box.

File NavigationStarting with MATLAB 6, Mathworks (the MATLAB creators) incorporated new features to easily navigate through your files. The 'Current Directory' is shown just above the Command Window with the option of changing the current directory with just a click. In addition, there is a 'Current Directory' subwindow to the left of the Command Window that lists files in the current directory (you can show/hide it from the 'Desktop menu'), and gives you the option of opening, executing, editing, etc., with the click of the right button on your mouse. You can also change the directory there or add a particular directory to the MATLAB path so that it can access all the files in that directory automatically.

General MATLAB commandsThese are Matlab commands to be used for on-line help, directory information, workspace information, general information and Matlab termination.

These functions can be used within scripts or from the command window

On-line helphelp lists topics on which help is availablehelpwin opens the interactive help windowhelpdesk opens the web browser based help facilityhelp topic provides help on topiclookfor string lists help topics containing stringdemo runs the demo program

Directory informationpwd shows the current working directorycd changes the current working directorydir lists files within the current directory

Page 6: Matlab Exer

ls lists contents of the current directory, same as dirpath gets or sets MATLAB search patheditpath modifies MATLAB search pathcopyfile copies a filemkdir creates a directory

Workspace informationwho lists variables currently in the workspacewhos lists variables in the workspace with their sizeclear all variables are removedclear x y z clears only variables x, y and zclear all clears all variables and functions from workspacemlock fun locks function fun so that 'clear' cannot remove itmunlock fun unlocks function fun so that 'clear' can remove itclc clears command window, command history is lostclose all closes all of the figure windows

       General informationcomputer tells you the computer type you are usingclock gives you clock time and date as a vectordate gives you the date as a stringver shows the license and the version information about

MATLAB installed on your computer

benchbenchmarks your computer on running MATLAB compared to other computers

Termination^c (Ctl-c) local abort, kills the current command executionquit quits MATLABexit same as quit

More MATLAB Commands...On this page we present the use of some very basic MATLAB commands and functions. With

Matlab, you can perform simple operations, as if you were working with a calculator.

Operation Symbol ExampleAddition, a+b + 5 + 3Subtraction, a-b - 20 - 9Multiplication, ab * 8.7 * 9.2Division, a/b / 40 / 8

Page 7: Matlab Exer

Power, ab ^ 5^3

Common Functionsabs(x) absolute valueacos(x) inverse cosine, result in radiansangle(x) angle of complex numberasin(x) inverse sine, result in radiansatan(x) inverse tangentceil(x) round towards plus infinityconj(x) complex conjugatecos(x) cosineexp(x) exponentialfix(x) round towards zerofloor(x) round towards minus infinityimag(x) complex imaginary partlog(x) natural logarithmlog10(x) common (base 10) logarithmreal(x) complex real partround(x) round towards nearest integersign(x) signum functionsin(x) sinesqrt(x) square roottan(x) tangent

Matlab doesn't care about spaces between operands, and multiplications are performed before additions. Type these operations on the command window (only the part just after '>>', and Matlab will give the answers): >> 2 + 1 + 3ans = 6

>> 8*9 - 6*5 + 3*4ans = 54

>> x=2x = 2

>> y=3y = 3

Page 8: Matlab Exer

>> cos(x)+sqrt(y)+tan(x+y)ans = -2.0646>>

You can keep values in variables:

>> apples=2apples =     2

>> bananas=5bananas =     5

>> peaches=4peaches =     4

>> fruit=apples+bananas+peachesfruit =    11

Ending the instruction with a ';' sign tells Matlab to make the operation but not to display the answer.

To see a list of your variables in memory you can use the commands 'who' or 'whos'.

>> whosName Size Bytes Class

ans 1x1 8 double arrayapples 1x1 8 double arraybananas 1x1 8 double arrayfruit 1x1 8 double arraypeaches 1x1 8 double array

Grand total is 5 elements using 40 bytes

Page 9: Matlab Exer

Variables are sensitive to lower/upper case. They have to start with a letter and can contain also numbers and underscores.

Special Names Valueans Default for resultspi 3.141592...eps Smallest possible number in Matlabinf InfiniteNaN Not a numberi square root of -1j square root of -1

To delete variables you can use the 'clear' command.

Operations with Complex Numbers

>> c1 = 1 - 2i c1 =   1.0000 - 2.0000i

>> c2 = 6 - 9jc2 =   6.0000 - 9.0000i

>> c3 = sqrt(-2)c3 =        0 + 1.4142i

>> c4 = c1 + c2 - c3c4 =   7.0000 -12.4142i>>

M-filesMatlab allows you to place your commands on a simple text file. You should name this file with the '.m' extension. Giving Matlab the name of this file while in the command window, makes Matlab to execute the script.

For example, name a text file 'primer.m'.Make it contain the following text:

Page 10: Matlab Exer

a = 3; b = -4; c = 8;d = a*b-c

When you execute this from the command window

>> primer

you obtain this information from MATLAB:

d  =

-20

M-File functionsdisp(ans) show results without showing the variable nameinput prompt for user inputkeyboard stops execution of the m-file and gives control to the

user's keyboard ('return' to quit)pause causes a procedure to stop and wait for the user to

strike any key before continuingpause(n) pauses for n secondswaitforbuttonpress wait for key/buttonpress over figure

Vectors

In Matlab, you can form arrays of numbers  - vectors or matrices - in a straight and intuitive way:

>> a  =  [2  4  6  9  -1  3]

means a row vector with values in variable 'a'a  = 2    4    6    9    -1    3

The numbers of the array should be separated by spaces (like shown) or commas. If you're working with complex numbers, you must avoid spaces and work only with commas.

There are simple ways to create horizontal arrays (row vectors) that increase or decrease in a linear pattern. For example, let's say thatyou wish to have a vector t to contain eleven values equally spaced from 0 to ¶. You can do this in at least three ways:

Page 11: Matlab Exer

>>  t  =  [0  .1*pi  .2*pi  .3*pi  .4*pi  .5*pi  .6*pi  .7*pi  .8*pi  .9*pi  pi]

>>  t  =  (0 : 0.1 : 1)*pi

>> t  =  linspace(0,pi,11)

The Matlab result is exactly the same:

t =

Columns  1  through  7

0    0.3142    0.6283    0.9425    1.2566    1.5708    1.8850

Columns  8  through  11

2.1991    2.5133    2.8274    3.1416

In the first case, you only place the numbers one by one, which is a very boring way to do it...

In the second case, you create an array which starts with 0, an then you increment the value in 0.1 steps until you get to 1. Then, every number is multiplied by ¶.

In the third case, you use the linspace function, which has the following arguments: linspace(start_value, end_value, number_of_values)

Obviously, the latest two ways are much better than the first way to do it.

Vector ConstructionYou create a row vector x specifing the numbers, one by one:

x  =  [1  3  9  33  0  -2]

You create a row vector x starting with a first value until you get to a last value, in steps of 1.

x  =  first: last   

You create a row vector x starting with a first value until you get to a last value, in specified increments.

x  =  first: increment: last

You create a row vector x starting with a first value until you get to a last value, in equally

Page 12: Matlab Exer

spaced n elements.

x  =  linspace(first, last, n)   

To acces each element of the vector you use subscripts. For example, x(1) is the first element of the vector x.

To acces a group of contiguous elements, you also use subscripts. For example, x(1:5) represents five elements, from element 1 to element 5 of the array.

Other examples:x(4 : -1 : 1) represents elements 4, 3, 2 and 1, in this order.x(2 : 2 : 7) represents elements 2, 4, and 6.                   

To work with column vectors, you put a ';' between each element.

>> b  =  [1;  2;  3;  4;  5]

b =     1     2     3     4     5

>>

You may use the transpose operator ('), to convert a row vector into a column vector.

>> a  =  1:5

a  =

1    2    3    4    5

>> b  =  a'

b =     1

Page 13: Matlab Exer

     2     3     4     5

>> x=(2:3:15)'

x =     2     5     8    11    14

>>

The Magic Square (an introduction to matrices)In Matlab, a matrix is a rectangular array of numbers. A scalar is a special 1-by-1 matrix, and matrices with only one row or column, are vectors. The operations in Matlab are designed to be as natural as possible.  Some programming languages work with numbers one at a time,  but Matlab allows you to work with entire matrices easily and quickly.  

There is a good and famous matrix, which appears in the Renaissance engraving Melencolia I, by the German artist Albrecht Durer. Click here to see the famous image (opens a new window).

The image is filled with mathematical symbolism, and if you look carefully, you will see a matrix in the upper right corner.

This matrix is known as a magic square and was believed by many in Durer’s time to have real mystical properties. It does have some interesting characteristics worth exploring.

The best way for you to get started with Matlab is to learn how to handle matrices. You can enter matrices into Matlab in several different ways:

Page 14: Matlab Exer

Load matrices from external data files. Enter your explicit list of elements. Generate matrices using built-in functions or with your own functions in m-files.

Enter Durer’s matrix as a list of elements. You only have to follow a few conventions:

Separate the elements of a row with blanks or commas. Use a semicolon ';'  to indicate the end of rows. Surround the entire list of elements with square brackets '[ ]'.

To enter Durer’s matrix, simply type in the Command WindowM = [16 3 2 13;  5 10 11 8;  9 6 7 12;  4 15 14 1]

Matlab displays the matrix you just entered.

M =16 3 2 135 10 11 89 6 7 124 15 14 1

This matches the numbers in the picture. Once you have entered the matrix, you can refer to it simply as 'M'. Now that you have M in the workspace, take a look at what makes it so appealing. Is it a magic square?

You are probably aware that the special properties of a magic square have to do with the various ways of summing its elements. If you take the sum along any column or row, or along either of the two diagonals, you will always get the same number. Let us verify that using Matlab. The first statement to try is sum(M)

Matlab replies with

ans =34 34 34 34

When you do not specify an output variable, Matlab uses the variable ans, to store the results of a calculation. You have found a row vector containing the sums of the columns of M, and each of the columns has the magic sum, 34.

How about the row sums? The easiest way to get the row sums is to transpose the matrix,

Page 15: Matlab Exer

compute the column sums of the transpose, and then transpose the result. The transpose operation is denoted by an apostrophe, '. It flips a matrix about its main diagonal and turns a row vector into a column vector.

So, M' produces

ans =16 5 9 43 10 6 152 11 7 1413 8 12 1

And sum(M')' produces a column vector containing the row sums

ans =34343434

The sum of the elements on the main diagonal is obtained with the sum and the diag functions.

diag(M) produces

ans =161071

and sum(diag(M)) produces

ans =34

You have verified that the matrix in Durer’s engraving is indeed a magic square and have tried a few Matlab matrix operations.

The element in row i and column j of M is denoted by M(i,j). For example, M(3,2) is the number in the third row and second column. For our magic square, M(3,2) is 6. So, to compute the sum of the elements in the third column of M, type

Page 16: Matlab Exer

M(1,3) + M(2,3) + M(3,3) + M(4,3)

This produces

ans =34

It is also possible to refer to the elements of a matrix with a single subscript, M(k). This is the common way of referencing row and column vectors. But it can also apply to a fully two-dimensional matrix, in which case the array is regarded as one long column vector formed from the columns of the originalmatrix. So, for our magic square, M(6) is another way of referring to the value 10 stored in M(2,2).

The colon ‘:’ is one of the most important Matlab operators. It occurs in several different forms. The expression 1:8 is a row vector containing the integers from 1 to 8

1 2 3 4 5 6 7 8

To obtain spacing, specify an increment. For example, 100 : -7 : 70 is

100    93    86    79    72

and 0 : pi/10 : pi/2 is

0    0.3142    0.6283    0.9425    1.2566    1.5708

Subscript expressions involving colons refer to sections of a matrix. M(1:k , j) is the first k elements of the jth column of M. So, sum(M(1:4,4)) computes the sum of rows 1 to 4, along column 4.

But there's even a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. So, sum(M(:,end)) computes the sum of the elements in the last column of M.

ans =34

Matlab actually has a built-in function that creates magic squares. This function is named

Page 17: Matlab Exer

'magic'. So, N = magic(4) displays a 4-by-4 matrix

N =16 2  3  135  11 10 89  7  6  124  14 15 1

This matrix is almost the same as the one in the Durer's picture and has all the same magic properties; the only difference is that the two middle columns are exchanged. Noticed?

To make this N into Durer’s M, swap the two middle columns:M = N(: , [1 3 2 4]). This means, for each of the rows of matrix N, reorder the elements in the order 1, 3, 2, 4. It produces

M =16 3  2  135  10 11 89  6  7  124  15 14 1

MatricesThe terms matrices and arrays are often used interchangeably. A matrix is a two-dimensional array of

real or complex numbers that represent something.

The algebraic operations defined on matrices have applications in a broad variety of technical fields. Matlab has dozens of functions that create different kinds of matrices. Arrays of numbers can also compose matrices. To create a matrix, spaces or commas separate the elements in columns, semicolons separate rows.

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

g  =

1    2    3    45    6    7    8

In this case g is a matrix of 2 rows and 4 columns (2x4).Naturally, all of the rows must have the same number of columns.

Math with matrices and scalars

Page 18: Matlab Exer

To an array or matrix, arithmetic with scalars equal to perform the operation of every element with the scalar.

>>  g+3           

ans  =            4    5    6    78    9    10    11

>>  2*g-2           

ans  =            0    2    4    68    10    12    14

Math between matricesWhen two arrays have the same dimensions, you can add or subtract one to/from the other element by element, like this:

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

A  =

1     2     3     45     6     7     89    10    11    12

>>  B  =  [1  1  1  1;  2  2  2  2;  2  2  2  2]

B  =

1    1    1    12    2    2    22    2    2    2

>>  A  +  B           

ans  =            2      3     4      57      8     9      1011    12    13    14

>> 2*A  -  B

ans  =

Page 19: Matlab Exer

1      3     5     78      10   12    1416    18    20    22

For multiplication, division or power operations, you use the 'element-wise' operators (with '.*', './', or '.^').

>>  A.*B

ans  =                1      2     3      4    10    12    14    16    18    20    22    24   

>>  A./B               

ans  =                1.0000    2.0000    3.0000    4.00002.5000    3.0000    3.5000    4.00004.5000    5.0000    5.5000    6.0000

>>  A.^2                ans  =                1      4       9       16    25     36     49     64    81    100    121    144   

Matrix AddressingThis notation refers to the element of row r and column c within matrix A.A(r, c)   

This notation refers to all of the elements of row r in matrix A.A(r, :)       

This notation refers to all of the elements of column c in matrix A.A(:, c)       

Matrix Functions det(A) determinant of the square matrix Ainv(A) inverse of the square matrix Anorm(A) largest singular value of Arank(A) provides an estimate of the number of

Page 20: Matlab Exer

linearly independent rows or columns of a matrix Atrace(A) sum of the diagonal elements of A, which is also the sum

of the eigenvalues of A

Special Matriceseye(N) is the N-by-N identity matrixmagic(N) an N-by-N matrix constructed from the integers 1

through N^2ones(N) an N-by-N matrix of onesrand(N) an N-by-N matrix containing pseudo-random values

drawn from a uniform distribution on the unit interval.zeros(N) an N-by-N matrix of zeros

Examples: Basic Matlab CodesBelow you can find examples on different types of arithmetic, exponential, trigonometry and complex number operations handled easily with MATLAB codes.

To code this expression: , you can write the following instruction in the Matlab command window (or within an m-file):

>> 5^3/(2^4+1)

ans =

    7.3529

To compute this formula:  , you can always break down the commands and simplify the code (a final value can be achieved in several ways).

>>numerator = 3 * (sqrt(4) - 2)numerator =

     0

>>denominator = (sqrt(3) + 1)^2

Page 21: Matlab Exer

denominator =

    7.4641

>>total = numerator/denominator – 5

total =

    -5

The following expression:  , can be achieved as follows (assuming that x and y have values already):

>> exp(4) + log10(x) - pi^y

The basic MATLAB trigonometric functions are 'sin', 'cos', 'tan', 'cot', 'sec', and 'csc'. The inverses, are calculated with 'asin', 'atan', etc. The inverse function 'atan2' takes two arguments, y and x, and gives the four-quadrant inverse tangent. Angles are in radians, by default.

The following expression:  , can be coded as follows (assuming that x has a value already):

>>(sin(pi/2))^2 + tan(3*pi*x).

MATLAB recognizes the letters i and j as the imaginary number. A complex number 4 + 5i may be input as 4+5i or 4+5*i in MATLAB.  The first case is always interpreted as a complex number, whereas the latter case is taken as complex only if i has not been assigned any local value.

Can you verify in MATLAB this equation (Euler's Formula)? You can do it as an exercise!

Examples: Simple Vector Algebra

Page 22: Matlab Exer

On this page we expose how simple it is to work with vector algebra, within Matlab.

Reproduce this example in MATLAB:

x = [2 4 6 8];y = 2*x + 3

y = 7    11    15    19

Row vector y can represent a straight line by doubling the x value (just as a slope = 2) and adding a constant.

Something like y = mx + c. It's easy to perform algebraic operations on vectors since you apply the operations to the whole vector, not to each element alone.

Now, let's create two row vectors (v and w), each with 5 linearly spaced elements (that's easy with function 'linspace':

v = linspace(3, 30, 5)w = linspace(4, 400, 5)

Obtain a row vector containing the sine of each element in v:

x = sin(v)

Multiply these elements by thir correspondig element in w:

y = x .* w

And obtain MATLAB's response:

y =

    0.5645  -32.9105 -143.7806 -286.4733 -395.2126

>>

Did you obtain the same? Results don't appear on screen if you end the command with the ';' sign.

y = x .* w;

You can create an array (or matrix) by combining two or more vectors:

Page 23: Matlab Exer

m = [x; y]

The first row of m above is x, the second row is y.

m =

    0.1411   -0.3195   -0.7118   -0.9517   -0.9880    0.5645  -32.9105 -143.7806 -286.4733 -395.2126

>>

You can refer to each element of m by using subscripts. For example, m(1,2) = -0.3195 (first row, second column); m(2,1) = 0.5645 (second row, first column).

You can manipulate single elements of a matrix, and replace them on the same matrix:

m(1,2) = m(1,2)+3m(2,4) = 0m(2,5) = m(1,2)+m(2,1)+m(2,5)

m =

    0.1411    2.6805   -0.7118   -0.9517   -0.9880    0.5645  -32.9105 -143.7806         0 -391.9677

>>

Or you can perform algebraic operations on the whole matrix (using element-by-element operators):

z = m.^2

z =

  1.0e+005 *

    0.0000    0.0001    0.0000    0.0000    0.0000    0.0000    0.0108    0.2067         0    1.5364

Page 24: Matlab Exer

>>

MATLAB automatically presents a coefficient before the matrix, to simplify the notation. In this

case 

Examples: MATLAB PlotsIn this group of examples, we are going to create several MATLAB plots.

We are going to produce some figures with simple scripts to show first a small number of points, and we'll show then more points to see how this affect the general image.

2D Cosine Plot

y=cos(x), for

You can type this in an 'm-file':

% Simple script to plot a cosine% vector x takes only 10 valuesx = linspace(0, 2*pi, 10);y = cos(x);plot(x,y)xlabel('x')ylabel('cos(x)')title('Plotting a cosine')grid on

The result is:

Page 25: Matlab Exer

If we use 100 points rather than 10, and evaluate two cycles instead of one (like this):

x = linspace(0, 4*pi, 100);

We obtain a different curve: 

 Now, a variation with line-syles and colors (type 'help plot' to see the options for line-types and colors):

clear; clc; close all;% Simple script to plot a cosine% vector x takes only 10 valuesx = linspace(0, 4*pi, 100);y = cos(x);plot(x,y, 'ro')xlabel('x (radians)')ylabel('cos(x)')title('Plotting a cosine')grid on

 

Page 26: Matlab Exer

Space curve

Use the command plot3(x,y,z) to plot the helix:

If  x(t)=sin(t), y(t)=cos(t), z(t)=(t) for every t in  ,then, you can type this code in an 'm-file' or in the command window:

% Another way to assign values to a vectort = 0 : pi/50 : 10*pi;plot3(sin(t),cos(t),t);

 

You can use the 'help plot3' command to find out more details.

Examples: MATLAB programming - Script Files -In this example, we are going to program the plotting of two concentric circles and mark the center point with a black square. We use polar coordinates in this case (for a variation).

We can open a new edit window and type the following program (script). As already mentioned, lines starting with a '%' sign are comments, and are ignored by MATLAB but are very useful to the viewer.

% The initial instructions clear the screen, all% of the variables, and close any figureclc; clear; close all

Page 27: Matlab Exer

% CIRCLE - A script file to draw a pretty circle% We first generate a 90-element vector to be used as an angleangle = linspace(0, 2*pi, 90);

% Then, we create another 90-element vector containing only value 2r2 = linspace(2, 2, 90);

% Next, we plot a red circle using the 'polar' functionpolar(angle, r2, 'ro')title('One more Circle')

% We avoid deletion of the figurehold on

% Now, we create another 90-element vector for radius 1r1 = linspace(1, 1, 90);polar(angle, r1, 'bx')

% Finaly, we mark the center with a black squarepolar(0, 0, 'ks')

We save the script and run it with the 'run' icon (within the Editor):

 

Or we can run it from the Command Window by typing the name of the script.

We now get the concentric circles:

Page 28: Matlab Exer

EXAMPLES: a custom-made Matlab function

Even though Matlab has plenty of useful functions, in this example we're going to develop a custom-made Matlab function. We'll have one input value and two output values, to transform a given number in both Celsius and Farenheit degrees.

A function file ('m-file') must begin with a function definition line. In this line we define the name of the function, the input and the output variables.

Type this example in the editor window, and assign it the name 'temperature' ('File' -> 'New' -> 'M-File'):

% This function is named 'temperature.m'.% It has one input value 'x' and two outputs, 'c' and 'f'. % If 'x' is a Celsius number, output variable 'f'% contains its equivalent in Fahrenheit degrees.% If 'x' is a Fahrenheit number, output variable 'c'% contains its equivalent in Celsius degrees. % Both results are given at once in the output vector [c f] function [c f] = temperature(x)f = 9*x/5 + 32;c = (x - 32) * 5/9;

Then, you can run the Matlab function from the command window, like this:

>> [cent fahr] = temperature(32)

cent =     0

fahr =   89.6000

Page 29: Matlab Exer

>> [c f]=temperature(-41)

c =  -40.5556

f =  -41.8000

The receiving variables ([cent fahr] or [c f]) in the command window (or in another function or script that calls 'temperature') may have different names than those assigned within your just created function.

Matlab Examples - matrix manipulationIn this article we study and experiment with matrix manipulation and boolean algebra. These Matlab examples create some simple matrices and then combine them to form new ones of higher dimensions. We also extract data from certain rows or columns to form matrices of lower dimensions.

Let's follow these Matlab examples of commands or functions in a script.

Example:

a = [1 2; 3 4]

b = [5 6     7 9]

c = [-1 -5; -3 9]

d = [-5 0 4; 0 -10 3]

e =  [8 6 4       3 1 8       9 8 1]

Note that a new row can be defined with a semicolon ';' as in a, c or d, or with actual new rows, as in b or e.

You can see that Matlab arranges and formats the data as follows:

Page 30: Matlab Exer

a =     1     2     3     4

b =     5     6     7     9

c =    -1    -5    -3     9

d =    -5     0     4     0   -10    3

e =     8     6     4     3     1     8     9     8     1

Now, we are going to test some properties relative to the boolean algebra...

We can use the double equal sign '==' to test if some numbers are the same. If they are, Matlab answers with a '1' (true); if they are not the same, Matlab answers with a '0' (false).  See these interactive examples:

Is matrix addition commutative?

a + b == b + a

Matlab compares all of the elements and answers:

ans =     1     1     1     1

Yes, all of the elements in a+b are the same than the elements in b+a.

Is matrix addition associative?

(a + b) + c == a + (b+c) Matlab compares all of the elements and answers:

Page 31: Matlab Exer

ans =     1     1     1     1

Yes, all all of the elements in (a + b) + c are the same than the elements in  a + (b+c).

Is multiplication with a matrix distributive?

a*(b+c) == a*b + a*c

ans =     1     1     1     1

Yes, indeed. Obviously, the matrices have to have appropriate dimensions, otherwise the operations are not possible.

Are matrix products commutative?

a*d == d*a

No, not in general.

a*d =     -5   -20    10   -15   -40    24

d*a  ... is not possible, since dimensions are not appropriate for a multiplication between these matrices, and Matlab launches an error:

??? Error using ==> mtimesInner matrix dimensions must agree.

Now, we combine matrices to form new ones:

g = [a b c] h = [c' a' b']'

Matlab produces:

g =

Page 32: Matlab Exer

     1     2     5     6    -1    -5     3     4     7     9    -3     9

h =    -1    -5    -3     9     1     2     3     4     5     6     7     9

We extract all the columns in rows 2 to 4 of matrix h

i = h(2:4, :)

Matlab produces:

i =    -3     9     1     2     3     4

We extract all the elements of row 2 in g (like this g(2, :)), transpose them (with an apostrophe, like this g(2, :)') and join them to what we already have in h. As an example, we put all the elements again in h to increase its size:

h = [h g(2, :)']

Matlab produces:

h =    -1    -5     3    -3     9     4     1     2     7     3     4     9     5     6    -3     7     9     9

Extract columns 2 and 3 from rows 3 to 6.

j = [h(3:6, 2:3)]

Page 33: Matlab Exer

And Matlab produces:

j =     2     7     4     9     6    -3     9     9

So far so good? Try it on your own!

Dot Product (also known as Inner or Scalar Product)The dot product is a scalar number and so it is also known as the scalar or inner product. In a real vector space, the scalar product between two vectors

is computed in the following way:

Besides, there is another way to define the inner product, if you know the angle between the two vectors:

 

We can conclude that if the inner product of two vectors is zero, the vectors are orthogonal.

In Matlab, the appropriate built-in function to determine the inner product is 'dot(u,v)'.

For example, let's say that we have vectors u and v, where

u = [1  0] and v = [2  2]. We can plot them easily with the 'compass' function in Matlab, like this:

Page 34: Matlab Exer

x = [1 2]y = [0 2]compass(x,y)

x represents the horizontal coordinates for each vector, and y represents their vertical coordinates. The instruction 'compass(x,y)' draws a graph that displays the vectors with components (x, y) as arrows going out from the origin, and in this case it produces: 

 

We can see that the angle between the two vectors is 45 degrees; then, we can calculate the scalar product in three different ways (in Matlab code):

a = u * v'b = norm(u, 2) * norm(v, 2) * cos(pi/4)c = dot(u, v)

Code that produces these results:a = 2b = 2.0000c = 2

Note that the angle has to be expressed in radians, and that the instruction 'norm(vector, 2)'

Page 35: Matlab Exer

calculates the Euclidian norm of a vector (there are more types of norms for vectors, but we are not going to discuss them here).

Cross Product - coded in a numerical softwareIn this example, we are going to write a function to find the cross product of two given vectors u and v.

If u = [u1 u2 u3] and v = [v1 v2 v3], we know that the product w is defined as w = [(u2v3 – u3v2) (u3v1 - u1v3) (u1v2 - u2v1)].

We can check the function by taking cross products of unit vectors i = [1 0 0], j = [0 1 0], and k = [0 0 1]

First, we create the function in an m-file as follows:

function w = crossprod(u,v)% We're assuming that both u and v are 3D vectors.% Naturally, w = [w(1) w(2) w(3)] w(1) = u(2)*v(3) - u(3)*v(2);w(2) = u(3)*v(1) - u(1)*v(3);w(3) = u(1)*v(2) - u(2)*v(1);

Then, we can call the function from any script, as follows in this example:

% Clear screen, clear previous variables and closes all figuresclc; close all; clear% Supress empty lines in the outputformat compact % Define unit vectorsi = [1 0 0];j = [0 1 0];k = [0 0 1]; % Call the previously created functionw1 = crossprod(i,j)w2 = crossprod(i,k)

Page 36: Matlab Exer

disp('*** compare with results by Matlab ***')w3 = cross(i,j)w4 = cross(i,k)

And Matlab displays:

w1 =     0     0     1w2 =     0    -1     0

*** compare with results by Matlab ***w3 =     0     0     1w4 =     0    -1     0>>

Complex Numbers

The unit of imaginary numbers is and is generally designated by the letter i (or j). Many laws which are true for real numbers are true for imaginary numbers as well.

Thus .

Matlab recognizes the letters i and j as the imaginary number .A complex number 3 + 10i may be input as 3 + 10i or 3 + 10*i in Matlab (make sure not to use i as a variable).

In the complex number a + bi, a is called the real part (in Matlab, real(3+5i) = 3) and b is the coefficient of the imaginary part (in Matlab, imag(4-9i) = -9). When a = 0, the number is called a pure imaginary. If b = 0, the number is only the real number a. Thus, complex numbers include all real numbers and all pure imaginary numbers.

The conjugate of a complex a + bi is a - bi. In Matlab, conj(2 - 8i) = 2 + 8i.

To add (or subtract) two numbers, add (or subtract) the real parts and the imaginary parts separately. For example:

Page 37: Matlab Exer

(a+bi) + (c-di) = (a+c)+(b-d)i

In Matlab, it's very easy to do it:>> a = 3-5ia = 3.0000 - 5.0000i

>> b = -9+3ib = -9.0000 + 3.0000i

>> a + bans = -6.0000 - 2.0000i

>> a - bans = 12.0000 - 8.0000i

To multiply two numbers, treat them as ordinary binomials and replace i2 by -1. To divide two complex nrs., multiply the numerator and denominator of the fraction by the conjugate of the denominator, replacing again i2 by -1.

Don't worry, in Matlab it's still very easy (assuming same a and b as above):>> a*bans = -12.0000 +54.0000i

>> a/bans = -0.4667 + 0.4000i

Employing rectangular coordinate axes, the complex nr. a+bi is represented by the point whose coordinates are (a,b).

We can plot complex nrs. this easy way. To plot numbers (3+2i), (-2+5i) and (-1-1i), we can write the following code in Matlab.

Page 38: Matlab Exer

Example - Plotting Complex Numbers:

% Enter each coordinate (x,y) separated by commas% Each point is marked by a blue circle ('bo')plot(3,2,'bo', -2,5,'bo', -1,-1,'bo')

% You can define the limits of the plot [xmin xmax ymin ymax]axis([-3 4 -2 6])

% Add some labels to explain the plotxlabel('x (real axis)')ylabel('y (imaginary axis)')

% Activate the gridgrid on

And you get:

Polar Form of Complex Nrs.

Page 39: Matlab Exer

In the figure below, .

Then .

Then x + yi is the rectangular form and is the polar form of the same complex

nr. The distance is always positive and is called the absolute value or modulus of the complex number. The angle is called the argument or amplitude of the complex number.

In Matlab, we can effortlessly know the modulus and angle (in radians) of any number, by using the 'abs' and 'angle' instructions. For example:

a = 3-4imagnitude = abs(a)ang = angle(a)

a = 3.0000 - 4.0000i

magnitude = 5

ang = -0.9273

De Moivre's Theorem

The nth power of is

Page 40: Matlab Exer

This relation is known as the De Moivre's theorem and is true for any real value of the exponent. If the exponent is 1/n, then

.

It's a good idea if you make up some exercises to test the validity of the theorem.

Roots of Complex Numbers in Polar Form

If k is any integer, .

Then,

Any number (real or complex) has n distinct nth roots, except zero. To obtain the n nth roots of the

complex number x + yi, or , let k take on the successive values 0, 1, 2, ..., n-1 in the above formula.

Again, it's a good idea if you create some exercises in Matlab to test the validity of this affirmation. Working with complex or imaginary numbers is easy with Matlab.

Future Value - how to calculate it using Matlab

This program is an example of a financial application in Matlab. It calculates the future value of an investment when interest is a factor.

It is necessary to provide the amount of the initial investment, the nominal interest rate, the number of compounding periods per year and the number of years of the investment.

Page 41: Matlab Exer

Assuming that there are no additional deposits and no withdrawals, the future value is based on the folowing formula:

where:

t = total value after y years (future value)y = number of yearsp = initial investmenti = nominal interest raten = number of compounding periods per year

We can achieve this task very easily with Matlab. First, we create a function to request the user to enter the data. Then, we perform the mathematical operations and deliver the result.

This is the function that requests the user to enter the necessary information:

function [ii, nir, ncppy, ny] = enter_valuesii = input('Enter initial investment: ');nir = input('Enter nominal interest rate: ');ncppy = input('Enter number of compounding periods per year: ');ny = input('Enter number of years: ');

This is the function that performs the operations:

function t = future_value(ii, nir, ncppy, ny)% Convert from percent to decimalni = nir / (100 * ncppy); % Calculate future value by formulat = ii*(1 + ni)^(ncppy * ny);% Round off to nearest centt = floor(t * 100 + 0.5)/100;

And finally, this is the Matlab code (script) that handles the above:

Page 42: Matlab Exer

% Instruction ‘format bank’ delivers fixed format for dollars% and cents% Instruction ‘format compact’ suppresses extra line-feedsclear; clc; format compactformat bank 

[ii, nir, ncppy, ny] = enter_values;t = future_value(ii, nir, ncppy, ny)

This is a sample run:

Enter initial investment: 6800Enter nominal interest rate: 9.5Enter number of compounding periods per year: 4Enter number of years: 10

with the result:

t = 17388.64

We can also test of the function, like this:

ii = 6800;nir = 9.5;ncppy = 4;ny = 10;t = future_value(ii, nir, ncppy, ny) 

with exactly the same result, as expected

t = 17388.64

Matlab Code - Loops, branches, and control-flowMATLAB code has its own instructions for control-flow statements like 'for-loops', 'while' and 'if-elseif' branching. Click on the links to see details and examples.

Iteration (for-loops)

Page 43: Matlab Exer

The MATLAB iteration structure (for-loop) repeats a group of statements a fixed, predetermined number of times. A matching end closes the statements.

Repeating then means looping or cycling a process usually with the objective of approaching a desired goal or target.

Each repetition of the process is called an 'iteration', and the results of

one turn are used as the starting point for the next turn or cycle.

The general format is:

for variable = expression statement ...end

Example:

c = 5;

% Preallocate matrix, fill it with zerosa = zeros(c, c);

for m = 1 : c for n = 1 : c a(m, n) = 1/(m + n * 5); endenda

The result is:

a = 0.1667 0.0909 0.0625 0.0476 0.0385 0.1429 0.0833 0.0588 0.0455 0.0370 0.1250 0.0769 0.0556 0.0435 0.0357 0.1111 0.0714 0.0526 0.0417 0.0345

Page 44: Matlab Exer

0.1000 0.0667 0.0500 0.0400 0.0333

The semicolon terminating the inner statement suppresses repeated printing,and the a after the loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested.

Matrix MultiplicationIf A is a matrix of dimension m x r, and B is a matrix of dimension r x n, you can find the product AB of dimension m x n by doing the following:

1. To find the element in row i and column j of matrix AB, you take row i of matrix A and column j of matrix B.

2. You multiply the corresponding elements of that row and that column and add up all the products.

In this example, we show a code in Matlab that performs a matrix multiplication step-by-step. The algorithm displays all the elements being considered for the multiplication and shows how the resulting matrix is being formed in each step. Obviously, Matlab can do it with just one operation (using the ' * ' operator, as in A*B), but we want to show every step of the process, as well as an example of how nested iterations work in Matlab.

Example:

% Clear screen, clear previous variables and closes all figuresclc; close all; clear% Avoid empty linesformat compact

% Define matrices, for example theseA = [2 1 4 1 2; 1 0 1 2 -1; 2 3 -1 0 -2]B = [-2 -1 2; 0 2 1; -1 1 4; 3 0 1; 2 1 2]

% The size of each matrix is considered for these calculations[r1 c1] = size(A);[r2 c2] = size(B);

% prevent unappropriate matrix sizeif c1 ~= r2    disp ('*** not able to multiply matrices ***')

Page 45: Matlab Exer

end

% Main code% Vary each row of matrix Afor i = 1 : r1    % Vary each column of matrix B    for j = 1 : c2        % Reset every new element of the final result        s = 0;        % Vary each column of matrix A and row of matrix B        for k = 1 : c1            % Display every element to take into account            A(i,k)            B(k,j)            % Prepare the addition in the iteration            s = s + A(i,k) * B(k,j);        end        % Assign the total of the appropriate element         % to the final matrix        C(i,j) = s    endend

% Compare our result with a multiplication by MatlabA*B

Matlab displays the following results:

 A =     2     1     4     1     2     1     0     1     2    -1     2     3    -1     0    -2B =    -2    -1     2     0     2     1    -1     1     4     3     0     1     2     1     2

then, the command window shows all the elements being considered and how the product AB (C) is being formed, and finalizes with our result and the multiplication achieved by Matlab itself.

Page 46: Matlab Exer

C =    -1     6    26     1    -1     6    -7     1    -1ans =    -1     6    26     1    -1     6    -7     1    -1

Control Structures (while statement loop)Among the control structures in programming languages, there is the while... end loop which repeats a

group of statements an indefinite number of times under control of a logical condition.

Syntax:while expression    statements     ...end

Example:

counter = 100;

while (counter > 95)   disp ('counter is still > 95')   counter = counter -1;enddisp('counter is no longer > 95')

Matlab response is:

counter is still > 95counter is still > 95counter is still > 95counter is still > 95counter is still > 95counter is no longer > 95

Page 47: Matlab Exer

>>

The cautions involving matrix comparisons that are discussed in the section on the if statement also apply to the while statement.

Square root algorithm (example on while-loops)   

In this short article we’ll explore a square root algorithm as an excuse to use while-loops in our numerical software. We’re not going to use the built-in function 'sqrt'.

Calculators typically implement routines to compute the exponential function and the natural logarithm, and then compute the root of a positive real number x using this identity:

We’ll follow a different approach: an iterative method using while-loops.

The most common iterative method of square root calculation is known as the ‘Heron's method’ or ‘Babylonian method’. 

First step, estimate a number. Think of this number as your first approach to a root (the closer to the actual square root of x, the fewer iterations will be needed to achieve the desired precision). 

Second step, divide your number by this (known inexact) square root. 

Third step, take the average of the result of the second step and ‘the root’. 

Fourth step, use the result of the third step to repeat steps 2 and 3 until you have a number that is accurate enough for you. 

The technique is a variation of the Newton-Raphson iterative solution method and it involves a simple algorithm, which results in a number closer to the actual square root each time it is repeated. 

Page 48: Matlab Exer

A code that accomplishes the algorithm is: 

function ta = sr(x)% Choose (arbitrarily) a first approachfa = x/2;% Divide your number by that first approachsa = x/fa;% Get the mean between the two previous numbersta = mean([fa sa]); 

% Repeat until you obtain a good enough rootwhile abs(x - ta^2) > 0.000000001    fa = ta;    sa = x/fa;    ta = mean([fa sa])end 

We can use or try our function like this, from the command window for example: 

format longy1 = sr(10)y2 = sqrt(10)

ta =    3.17857142857143ta =    3.16231942215088ta =    3.16227766044414ta =    3.16227766016838

 Our algorithm needed four iterations to obtain the final result (in y1, below). Note that only two iterations were needed to have an accuracy within three decimals. y2 is the result from the function ‘sqrt’, to compare with. 

y1 =    3.16227766016838y2 =    3.16227766016838 

Another example,

y3 = sr(255)y4 = sqrt(255) 

Page 49: Matlab Exer

ta =   34.34411196911197ta =   20.88448273516376ta =   16.54725251948965ta =   15.97883290053478ta =   15.96872262323155ta =   15.96871942267163 

Our algorithm needed six iterations to obtain the final result (in y3, below). Note that only four iterations were needed to have an accuracy within one decimal. y4 is the result from the function ‘sqrt’, to compare with. 

y3 =   15.96871942267163y4 =   15.96871942267131

if statement - BranchesThe if statement evaluates a logical expression and executes a group of statements when the expression is true.

The optional elseif and else keywords provide for the execution of alternate groups of statements.

An end keyword, which matches the if, terminates the last group of statements.

This type of structure is also known as branches or 'branching'.

The groups of statements are delineated by the four keywords (no braces orbrackets are involved).

The general form of the statement is:

if expression1    statements1    ...elseif expression2    statements2    ...else    statements3    ...end

Page 50: Matlab Exer

It is important to understand how relational operators and if statements work with matrices.

When you want to check for equality between two variables, you might use if A == B ...

This '==' code is fine, and it does what you expect when A and B are scalars.

But when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0’s and 1’s showing element-by-element equality.

In fact, if A and B are not the same size, then A == B is an error.

The proper way to check for equality between two variables is to use theisequal function:

if isequal(A,B) ...

Here's an example code:

if m == n   a(m,n) = 3;elseif abs(m-n) == 3   a(m,n) = 1;else   a(m,n) = 0;end

If m equals n, then a(m,n) becomes 3, and the routine continues after the end.

If not, the routine tests if abs(m-n) equals 3. If it does, then a(m,n) becomes 1, and the routine continues after the end.

In any other case a(m,n) becomes 0, and the routine continues after the end.

Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including:

isequalisemptyallany

Page 51: Matlab Exer

' break ' statement

The break statement lets you exit early from a for or while loop. In nestedloops, break exits from the innermost loop only

Example 1:

for i = length(x)   % check for positive y   if y(x) > 0      % terminate loop execution      break   end   % follow your code   a = a + y(x);   ...end

Example 2:

x = sin(sqrt(variable));while 1   n = input('Enter number of loops: ')   if n <= 0      % terminate loop execution      break   end   for i = 1 : n      % follow your code      x = x + 20;      ...   endend

Matrix Inversion

This program performs the matrix inversion of a square matrix step-by-step. The inversion is performed by a modified Gauss-Jordan elimination

Page 52: Matlab Exer

method. We start with an arbitrary square matrix and a same-size identity matrix (all the elements along its diagonal are 1).

We perform operations on the rows of the input matrix in order to transform it and obtain an identity matrix, and

perform exactly the same operations on the accompanying identity matrix in order to obtain the inverse one.

If we find a row full of zeros during this process, then we can conclude that the matrix is singular, and so cannot be inverted.

We expose a very naive method, just as was performed in the old-Basic- style. Naturally, Matlab has appropriate and fast instructions to perform matrix inversions ('inv' or '\', for example), but we want to explain the Gauss-Jordan concept and show how nested loops and control flow work.

First, we develop a function like this (let's assume we save it as 'mat_inv2.m'):

function b = mat_inv2(a)% Find dimensions of input matrix[r,c] = size(a);

% If input matrix is not square, stop functionif r ~= c disp('Only Square Matrices, please') b = []; returnend

% Target identity matrix to be transformed into the output % inverse matrixb = eye(r);

%The following code actually performs the matrix inversionfor j = 1 : r for i = j : r

Page 53: Matlab Exer

if a(i,j) ~= 0 for k = 1 : r s = a(j,k); a(j,k) = a(i,k); a(i,k) = s; s = b(j,k); b(j,k) = b(i,k); b(i,k) = s; end t = 1/a(j,j); for k = 1 : r a(j,k) = t * a(j,k); b(j,k) = t * b(j,k); end for L = 1 : r if L ~= j t = -a(L,j); for k = 1 : r a(L,k) = a(L,k) + t * a(j,k); b(L,k) = b(L,k) + t * b(j,k); end end end end break end % Display warning if a row full of zeros is found if a(i,j) == 0 disp('Warning: Singular Matrix') b = 'error'; return endend% Show the evolution of the input matrix, so that we can % confirm that it became an identity matrix.a

And then, we can call it or test it from any other script or from the command window, like this:

% Input matrixa = [3  5  -1   -4     1  4  -.7  -3     0 -2   0    1    -2  6   0   .3];

Page 54: Matlab Exer

% Call the function to find its inverseb = mat_inv2(a)

% Compare with a result generated by Matlabc = inv(a)

Matlab produces this response:

First, we see how the original matrix transformet into an identity matrix:

a = 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1

Then, our function show its result:b = 0.6544 -0.9348 -0.1912 0.0142 0.1983 -0.2833 -0.1034 0.1558 0.3683 -1.9547 -4.2635 -0.4249 0.3966 -0.5666 0.7932 0.3116

Finally, this is the inversion produced by a direct instruction from Matlab (inv(a)):c = 0.6544 -0.9348 -0.1912 0.0142 0.1983 -0.2833 -0.1034 0.1558 0.3683 -1.9547 -4.2635 -0.4249 0.3966 -0.5666 0.7932 0.3116

Another example:

% Input matrixa = [1 1 1 1];

% Call the function to find its inverse

Page 55: Matlab Exer

b = mat_inv2(a)

% Compare with a result generated by Matlabc = inv(a)

And Matlab display is:

Warning: Singular Matrixb =

error

Warning: Matrix is singular to working precision.> In test_mat_inv at 42

c = Inf Inf Inf Inf

In this case, our algorithm found a singular matrix, so an inverse cannot be calculated. This agrees with what Matlab found with its own built-in function.

Switch StatementAnother way to branch in programming

The switch statement in Matlab executes groups of instructions or statements based on the value of a variable or expression.

It's a type of selection control statement that exists in most modern imperative programming languages.

The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch.

The syntax is:

switch switch_expr  case case_expr     statement    ...

  case {case_expr1,case_expr2,case_expr3,...}    statement

Page 56: Matlab Exer

    ...

  otherwise    statement    ...end

MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.

Example:

To execute a certain block of code based on what the string 'color' is set to:

color = 'rose';

switch lower(color)   case {'red', 'light red', 'rose'}      disp('color is red')

   case 'blue'      disp('color is blue')

   case 'white'      disp('color is white')

   otherwise      disp('Unknown color.')end

Matlab answer is:

color is red

Boolean AlgebraThese are the four logical operators for Boolean Algebra in Matlab.It was named after George Boole, who first defined an algebraic system of logic in 19th. century.

Page 57: Matlab Exer

Boolean OperatorIn Matlab, there are four logical (aka boolean) operators:

Boolean operator: Meaning:

& logical AND

| logical OR

~ logical NOT (complement)

xor exclusive OR

These operators produce vectors or matrices of the same size as the operands, with 1 when the condition is true, and 0 when the condition is false.

Given array x = [0 7 3 5] and array y = [2 8 7 0], these are some possible operations:

Operation: Result:n = x & y               n = [0     1     1     0]m = ~(y | x)            m = [0     0     0     0]p = xor(x, y)           p = [1     0     0     1]

Since the output of the logical or boolean operations is a vector or matrix with only 0 or 1 values, the output can be used as the index of a matrix to extract appropriate elements. For example, to see the elements of x that satisfy both the conditions (x<y) and (x<4), you can type x((x<y)&(x<4)).

Operation: Result:x<y                     ans = [1     1     1     0]x<4                     ans = [1     0     0     0]q = x((x<y)&(x<4))      q = [0     3]

Additionally to these boolean operators, there are several useful built-in logical functions, such as:

any true if any element of a vector is true

all true if all elements of a vector are true

exist true if the argument exists

Page 58: Matlab Exer

isempty true for an empty matrix

isinf true for all infinite elements of a matrix

isnan true for all elements of a matrix that ara not-a-number

find finds indices of non-zero elements of a matrix

Relational OperatorsThere are six relational operators in Matlab:

Relational operator: Meaning:

< less than

<= less than or equal

> greater than

>= greater than or equal

== equal (possibility, not assignation)

~= not equal

These operations result in a vector of matrix of the same size as the operands, with 1 when the relation is true, and 0 when it’s false.

Given arrays x = [0 7 3 5] and y = [2 8 7 0], these are some possible relational operations:

Operation: Result:k = x<y                 k = [1     1     1     0]k = x <= y              k = [1     1     1     0]

k = x == y              k = [0     0     0     0]

Although these operations are usually used in conditional statements such as if-else to branch out to different cases, they can be used to do very complex matrix manipulation. For example x = y(y > 0.45) finds all the elements of vector y such that yi > 0.45 and stores them in vector x. These operations can be combined with boolean operators, too.

Page 59: Matlab Exer

Logical AND

We're going to examine a couple of examples on boolean operators in Matlab. These operators are useful when we want to develop logic functions in our code. Naturally, we can combine several operations do accomplish very complex functions. Let's start with the basics...

A & B performs a logical AND of arrays A and B and returns an array containing elements set to either logical 1 (TRUE) or logical 0 (FALSE).

A B A & B 0 0 00 1 01 0 01 1 1

This is a logical AND Gate, as used in electronic circuits

An element of the output array is set to 1 if both input arrays contain a non-zero element at that same array location. Otherwise, that element is set to 0. A and B must have the same dimensions unless one is a scalar. Example:

If matrix A is:A =

0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1

and matrix B is:B =

0 0 0 0 1 1 1 1 0 1 0 1 1 0 1 0

Page 60: Matlab Exer

Then, the AND operation between A and B is:

>> A & B

ans =

0 0 0 0 1 1 0 0 0 0 0 0 1 0 1 0

>>

Example:

If vector x is:x =

     0     1     2     3     0

and vector y is:y =

     1     2     3     0     0

Then, the AND operation between x and y is:

Page 61: Matlab Exer

>> x & y

ans =

     0     1     1     0     0Logical OR - (logic OR gate)

A | B performs a logical OR of arrays A and B and returns an array containing elements set to either logical 1 (TRUE) or logical 0 (FALSE). Sometimes, this operation is considered an 'addition' in terms of electronic gates. This is the truth table and the representation of an OR Gate as it's seen in digital electronics.

A B A | B 0 0 00 1 11 0 11 1 1

This is a logical OR Gate, as used in electronic circuits

An element of the output array is set to 1 if either input array contains a non-zero element at that same array location. Otherwise, that element is set to 0. A and B must have the same dimensions unless one is a scalar. This is a simple example on how you can code it in Matlab.

Example 1:

If matrix A is:A =

0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1

Page 62: Matlab Exer

and matrix B is:B =

0 0 0 0 1 1 1 1 0 1 0 1 1 0 1 0

Then, the OR operation between A and B is:

>> A | B

ans =

0 0 1 1 1 1 1 1 0 1 0 1 1 1 1 1

>>

Example 2:

If vector x is:x = 0 1 2 3 0

and vector y is:y = 1 2 3 0 0

Then, the OR operation between x and y is:

>> x | y

ans = 1 1 1 1 0

XOR - Logical EXCLUSIVE OR

Page 63: Matlab Exer

A B x o r (A,B) 0 0 00 1 11 0 11 1 0

For the logical exclusive OR, XOR(A,B), the result is logical 1 (TRUE) where either A or B, but not both, is nonzero. The result is logical 0 (FALSE) where A and B are both zero or nonzero.

A and B must have the same dimensions (or one can be a scalar).

This is the common symbol for the 'Exclusive OR'

Example:If matrix A is:A =

0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1

and matrix B is:B =

0 0 0 0 1 1 1 1 0 1 0 1 1 0 1 0

Then, the logical EXCLUSIVE OR between A and B is:

>> xor(A,B)

ans =

Page 64: Matlab Exer

0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1

>>

Example:If vector x is:x =

0 1 2 3 0

and vector y is:y =

1 2 3 0 0

Then, the logical exclusive OR between x and y is:

ans =

1 0 0 1 0

Logical NOT

In MATLAB, ~A performs a logical NOT of input array A, and returns an array containing elements set to either logical 1 (TRUE) or logical 0 (FALSE). This is the truth table and the representation of a NOT Gate as it's represented in digital electronics.

A ~A 0 11 0

This is a logical NOT gate, as represented in electronic circuits

Page 65: Matlab Exer

An element of the output array is set to 1 if A contains a zero value element at that same array location. Otherwise, that element is set to 0.

Example 1:If matrix A is:A =

0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1

Then, the NOT A is produced:

>> ~A

ans =

1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0

Example 2:If vector x is:x = 0 1 2 -3 0

Then, the NOT x is produced:

>> ~x

ans = 1 0 0 0 1

Page 66: Matlab Exer

Combinational logic - Basic Applications of Boolean GatesExperiments with electronic gates

Logic circuits can be divided into two major sections: combinational logic and sequential logic. The main difference is that the first type of circuit logic doesn’t depend on time or sequence of movements, and the second type of logic does.

A clear example to understand this difference can be illustrated by showing the two locks below

:

Combinational Logic Sequential Logic

The lock on the left has four discs that can be rotated separately. When the notches are aligned, the metal hook is released. The only one condition needed is that the appropriate four notches are aligned, no matter if the left disc is set before the one on the right. The lock will open if you have the correct combination. 

On the contrary, the lock on the right has only one knob, and the combination could be 3cw – 52ccw – 20cw. This means that one must first get to number 3 going clockwise, then to 52 counterclockwise, and finally get to number 20 clockwise. If you use the same numbers in different order, the lock won’t open. This is a sequential lock, a correct sequence is important. 

Due to its stability, reliability, low maintenance and ease at reading digital displays, these days everything is going the digital way. 

Logic circuits can be simulated with the so called boolean or logic gates. This is kind of Digital Electronics 101... 

Let’s say that we’d like to find out the behavior of the following combinational circuit: 

Page 67: Matlab Exer

 

 We can create an m-file to effortlessly solve the logic circuit, like this:

function f = combination(x)% x(1) = A% x(2) = B% x(3) = C% Symbol ~ is used for NOT gates 

% We have 4 logic-AND gatesand1 = ~x(1) & ~x(2) & ~x(3);and2 = ~x(1) & x(2)  & ~x(3);and3 = ~x(1) & ~x(2) & x(3);and4 = ~x(1) & x(2)  & x(3); 

% We have 1 logic-OR gatef = and1 | and2 | and3 | and4; 

We can test our function for this specific example of combinational logic: 

% These are all the possible combinations for 3 inputsM = [ 0 0 0      0 0 1      0 1 0      0 1 1      1 0 0      1 0 1      1 1 0      1 1 1]; 

Page 68: Matlab Exer

% We give all the combinations, one at a time for i = 1 : 8    comb_log(i) = combination(M(i, :));end 

% We display the resultscomb_log

 

The results are: 

comb_log =  1     1     1     1     0     0     0     0

  

If you make some analysis using the DeMorgan laws, you can conclude that this function can also be simplified to F = not(A), and you can visualize it from the results...

This means that we have not only a MATrix LABoratory, but we've got also a circuit logic simulator!

Calculus Problems - some ideas and approaches with MatlabCalculus problems are a branch of mathematics focused on limits, functions, derivatives and integrals.

This very broad topic constitutes a major part of modern education. It has two major branches, differential and integral calculus, which are related due to the fact that integrals are the anti-derivatives (so to speak).... We use Matlab to fastly experiment with some important concepts.

Sequences and SeriesSequences and series are very related: a sequence of

numbers is a function defined on the set of positive integers (the numbers in the sequence are called terms)...

Infinite and Harmonic SeriesIn this article we are going to experiment on geometric and harmonic series. We review geometric series, the alternating harmonic series, the Leibnitz formula to find pi and...

Page 69: Matlab Exer

FactorialsFactorials of positive integers n, are the product of all positive integers less than or equal to n. Factorials are denoted by n!...

Lucas SeriesThe French mathematician, E. Lucas, found a sequence of numbers (named the Lucas series) similar to the sequence found in the Fibonacci numbers.

DerivativeThe derivative of a function f(x) at x = c is the slope of the tangent line to f at x = c. You can find the value of the derivative using the difference quotient, which is a formula...

GradientIn our case, a numerical gradient is like having a 3D derivative. We get partial derivatives along x, y and z axes, and that's our gradient. It's convenient to follow the method shown to calculate derivatives...

Definite IntegralsA numerical integration can be performed by a number of algorithms that calculate the approximate value of definite integrals...

Trapezoidal RuleThe Trapezoidal Rule is a way to approximate area beneath a curve. Instead of constructing rectangles, this method uses small trapezoids. In effect, these trapezoids look the same as rectangles near their bases, but different at the top...

Simpson's RuleAnother area-approximating tool is the Simpson’s Rule. Geometrically, it creates parabolas to get closer to the function we’re approximating. The formula is similar to the trapezoidal rule, but you can only use an even number of subintervals...

Maclaurin SeriesMaclaurin series are fast approximations of functions, and they offer more accurate function approximations than just linear ones. You have to consider only one general formula and you can...

Taylor expansionTaylor series are another type of fast approximations of functions and are very similar to Maclaurin's. You have to consider only one general formula and you can...

Sine / Cosine seriesThe sine and cosine functions are two of the basic functions in trigonometry. In this article, we’re going to explore a number of ways to calculate the sine series without actually using the sine (or cosine)

Page 70: Matlab Exer

functions...

Fourier Analysis - introThis field began with the study of the way periodic or general functions that might be represented by summations of simpler trigonometric functions (sine or cosine series). Fourier analysis has many applications in science...

Fourier Series - (analysis cont.)Fourier series is an infinite sum of sines used to solve special types of problems in electronics. The series consists of an infinite sum of sines (and cosines) that repeats over fixed intervals...

Linear AlgebraHere are some important and requested topics regarding Linear Algebra. This type of algebra is a branch of mathematics related to the study of vectors (families of vectors or linear spaces), and with functions that enter one vector and produce another, according to certain rules. These functions are called linear maps and are usually represented by matrices. Linear algebra is quite relevant in modern math and its applications.

Determinants in MatlabThe determinant (in linear algebra) is a value associated with a square matrix, that is a matrix with as many rows as columns. It can be calculated from the elements of the matrix by a specific arithmetic

expression. The determinant provides important information in many types of problems, for example, when the matrix represent the coefficients of a system of linear equations...

The symbol

which consists of the four numbers a1, b1, a2, b2 arranged in two rows and two columns is called a determinant of second order or of order two. The four numbers are called its elements. By definition,

 

Page 71: Matlab Exer

Then, 

Here, the elements 2 and 3 are in the first row, and the elements 4 and 1 are in the second row. Elements 2 and 4 are in column one, and elements 3 and 1 are column two.

The method of solution of linear equations by determinants is called the Cramer’s Rule. A system of two linear equations in two unknowns may be solved using a second order det. Given the system of equations 

a1x + b1y = c1

a2x + b2y = c2

it is possible to obtain

These values for x and y may be written in terms of second order dets, as follows:

 

Example: 

Solve the system of equations:

2x + 3y = 164x + y = -3

The denominator for both x and y is

 

Page 72: Matlab Exer

Then and

In Matlab, a determinant can be calculated with the built-in function 'det()'.

Using the same numbers as in the example above,

if A = [2 3; 4 1], then det(A) = -10;if B = [16 3; -3 1], then x = det(A)/det(B) = -2.5;if C = [2 16; 4 -3], then y = det(C)/det(A) = 7

Naturally, you can use the function det() to find determinants of higher order.

Cramer's RuleThe method of solution of linear equations by determinants is called Cramer's Rule. This rule for linear equations in 3 unknowns is a method of solving -by determinants- the following equations for x, y, z

a1x + b1y + c1z = d1

a2x + b2y + c2z = d2

a3x + b3y + c3z = d3

If we analytically solve the equations above, we obtain

If  is the determinant of coefficients of x, y, z and is

 assumed not equal to zero, then we may re-write the values as 

Page 73: Matlab Exer

The solution involving determinants is easy to remember if you keep in mind these simple ideas:

The denominators are given by the determinant in which the elements are the coefficients of x, y and z, arranged as in the original given equations.

The numerator in the solution for any variable is the same as the determinant of the coefficients ∆ with the exception that the column of coefficients of the unknown to be determined is replaced by the column of constants on the right side of the original equations. 

That is, for the first variable, you substitute the first column of the determinant with the constants on the right; for the second variable, you substitute the second column with the constants on the rigth, and so on...

Example:

Solve this system using Cramer’s Rule

2x + 4y – 2z = -66x + 2y + 2z = 82x – 2y + 4z = 12

 

For x, take the determinant above and replace the first column by the constants on the right of the system. Then, divide this by the determinant:

Page 74: Matlab Exer

For y, replace the second column by the constants on the right of the system. Then, divide it by the determinant: 

For z, replace the third column by the constants on the right of the system. Then, divide it by the determinant:

You just solved ths system!

 

In Matlab, it’s even easier. You can solve the system with just one instruction.

Let D be the matrix of just the coefficients of the variables:

D = [2  4 -2;     6  2  2;     2 -2  4]; 

Let b be the column vector of the constants on the rigth of the system :

b = [-6 8 12]'; % the apostrophe is used to transpose a vector

Find the column vector of the unknowns by 'left dividing' D by b (use the backslash), like this:

variables = D\b

Page 75: Matlab Exer

And Matlab response is:

variables =    1.0000   -1.0000    2.0000   

Simultaneous Equations

- Linear Algebra Solving a system of simultaneous equations is easy in Matlab. It is, maybe, the most used operation in science and engineering, too. Solving a set of equations in linear algebra on a computer is nowadays as basic as doing arithmetic additions using a calculator. Let's see how easy Matlab makes this task.

Consider the following set of equations for our example.

-6x = 2y - 2z + 15 4y - 3z = 3x + 13 2x + 4y - 7z = -9

First, rearrange the equations.

Write each equation with all unknown quantities on the left-hand side and all known quantities on the right side. Thus, for the equations given, rearrange them such that all terms involving x, y and z are on the left side of the equal sign.

-6x - 2y + 2z = 15-3x + 4y - 3z = 13 2x + 4y - 7z = -9

Second, write the equations in a matrix form

To write the equations in the matrix form Ax = b, where x is the vector of unknowns, you have to arrange the unknowns in vector x, the coefficients of the unknowns in matrix A and the constants on the rigth hand of the equations in vector b. In this particualar example, the unknown column vector is

x = [x y z]'

the coefficient matrix is

Page 76: Matlab Exer

A = [-6 -2 2 -3 4 -3 2 4 -7]

and the known constant column vector is

b = [15 13 -9]'

Note than the columns of A are simply the coefficients of each unknown from all the three expressed equations. The apostrophe at the end of vectors x and b means that those vectors are column vectors, not row ones (it is Matlab notation).

Third, solve the simultaneous equations in Matlab

Enter the matrix A and vector b, and solve for vector x with the instruction 'x = A\b' (note that the '\' sign is different from the ordinary division '/' sign).

The Matlab answer is:

A = -6 -2 2 -3 4 -3 2 4 -7

b = 15 13 -9

x = -2.7273 2.7727 2.0909

You can test the result by performing the substitution and multiplying Ax to get b, like this:

Page 77: Matlab Exer

A*x

And the Matlab answer is:

ans = 15.0000 13.0000 -9.0000

which corresponds to column vector b, indeed.

Was this system of equations easy enough?

Linear Algebra and its Applications

- Circuit Analysis -One important linear algebra application is the resolution of electrical circuits. We can describe this type of circuits with linear equations, and then we can solve the linear system using Matlab.

For example, let's examine the following electrical circuit (resistors are in ohms, currents in amperes, and voltages are in volts):

We can describe the circuit with the following system of linear equations:

Page 78: Matlab Exer

7 - 1(i1 - i2) - 6 - 2(i1 - i3) = 0-1(i2 - i1) - 2(i2) - 3(i2 - i3) = 06 - 3(i3 - i2) - 1(i3) - 2(i3 - i1) = 0

Simplifying and rearranging the equations, we obtain:

-3i1 +  i2 + 2i3 = -1   i1 - 6i2 + 3i3 =  0 2i1 + 3i2 - 6i3 = -6

This system can be described with matrices in the form Ax = b, where A is the matrix of the coefficients of the currents, x is the vector of unknown currents, and b is the vector of constants on the right of the equalities.

One possible Matlab code to solve this is:

A = [-3  1  2        1 -6  3        2  3 -6];

b = [-1 0 -6]';

i = A\b

The Matlab answer is:

i =    3.0000    2.0000    3.0000

>>

This means that i1 = 3, i2 = 2, and i3 = 3.

Linear Programming - (as an optimization problem)

Page 79: Matlab Exer

Matlab is well suited to handle the so called linear programming problems. These are problems in which you have a quantity, depending linearly on several variables, that you want to maximize or minimize subject to several constraints that are expressed as linear inequalities with the same variables.

Sometimes the number of variables and the number of constraints are high, or the

constraints in the linear inequalities or the expression for the quantity to be optimized may be numerically complicated.

We will illustrate the method of linear programming by means of a simple example giving a numerical solution. Matlab has some special functions such as 'simlp' or 'linprog' to tackle down this type of problems, but these built-in functions are not always available since they belong to special toolboxes (Simulink or Optimization toolboxes). Therefore, we are going to formulate the problem as an optimization issue, and we'll use the instruction 'fminsearch', which is an always available instruction.

Let's suppose that a merry farmer has 75 roods (4 roods = 1 acre) on which to plant two crops: wheat and corn. To produce these crops, it costs the farmer (for seed, water, fertilizer, etc. ) $120 per rood for the wheat, and $210 per rood for the corn. The farmer has $15,000 available for expenses, but after the harvest the farmer must store the crops while awaiting favorable or good market conditions. The farmer has storage space for 4,000 bushels. Each rood yields an average of 110 bushels of wheat or 30 bushels of corn. If the net profit per bushel of wheat (after all the expenses) is $1.30 and for corn is $2.00, how should the merry farmer plant the 75 roods to maximize profit?

We begin by formulating the linear programming problem mathematically. We express the objective (profit) and the constraints. Let x denote the number of roods allotted to wheat and y the number of roods allotted to corn. Then the expression to be maximized is clearly

P = (110)(1.3)x + (30)(2)y = 143x + 60y

There are some constraint inequalities, specified by the limits on expenses, storage and roodage. They are:

and naturally:

As we mentioned before, we are going to formulate this as an optimization problem using the 'fminsearch' built-in function.

Page 80: Matlab Exer

 In Matlab, the instruction works as follows:

X = FMINSEARCH(FUN,X0,OPTIONS) minimizes with the default optimization parameters replaced by values in the structure OPTIONS, created with the OPTIMSET function. FMINSEARCH uses these options: Display, TolX, TolFun, MaxFunEvals, MaxIter, FunValCheck, and OutputFcn.

This is one possible approach for our objective function, which is saved as an m-file (in this case 'OF_P.m'):

function OFValue = OF_P(x)

% Here we embed the constraints or inequalities.% If the constraints are not met, we penalize the optimization by% giving an arbitrary high value to the objective function.if  120 * x(1) + 210 * x(2) > 15000 |...    110 * x(1) + 30 * x(2) > 4000 |...    x(1) + x(2) > 75 | ...    x(1) < 0 |...    x(2) < 0    OFValue = 10;    returnend

% fminsearch tries to minimize the function, so we invert its signP = 143 * x(1) + 60 * x(2);OFValue = -P;

Then, we can call it from another script, which includes the 'fminsearch'  function calling the objective function file (in 'OF_P'):

clear; clc; format bank

% We have to start with a 'seed' for the searchx = [1 10]';

% We can perform the optimization with different number of% iterations or tolerancesoptions = optimset('MaxFunEvals', 2000, 'TolX', 1e-2);

Page 81: Matlab Exer

[x_opt, FunVal, EF, output] = fminsearch('OF_P', x, options)

% Finally, we display the profit using the found solutionP = 143 * x_opt(1) + 60 * x_opt(2)

And the Matlab response is:

x_opt =         21.87         53.12

FunVal =      -6315.62EF =          1.00output =     iterations: 121.00     funcCount: 243.00     algorithm: 'Nelder-Mead simplex direct search'       message: [1x196 char]

P =       6315.62

This means that the farmer should consider 21.87 roods for wheat, 53.12 roods for corn, and his profit would be $6,315.62.

It is important to notice that this is a numerical approximation, which means that if we start with another 'seed' or use other parameters in the 'options' set, we can get to another result. The number found is a possible solution, but there's no guarantee that it is the best one, according to tolerances or to number of iterations or evaluations desired.

For example, we can use the seed 'x = [10 10]' instead (without moving any other instruction), and the Matlab answer now is:

x_opt =         32.31         14.88

Page 82: Matlab Exer

FunVal =      -5512.50EF =          1.00output =     iterations: 75.00     funcCount: 151.00     algorithm: 'Nelder-Mead simplex direct search'       message: [1x196 char]

P =       5512.50

Now, the 'best' profit found is only $5,512.50. So, it is a good idea to try with several 'seeds' and different parameters in the 'options' set to compare with and select the best solution. Most of the times the solutions will be very close (at least for linear programming problems).

LU FactorizationIn Matlab there are several built-in functions provided for matrix factorization (also called decomposition).

The name of the built-in function for a Lower-Upper decomposition is 'lu'. To get the LU factorization of a square matrix A, type the command '[L, U] = lu(A)'.

Matlab returns a lower triangular matrix L and an upper triangular matrix  U such that L*U = A.

Suppose that we need to perform a factorization on

A= [ 1  2 -3      -3 -4 13       2 1 -5]

We can verify that if matrix

L = [ 1   0     0      -3   1     0       2  -1.5  1]

and matrix

U = [1   2  -3

Page 83: Matlab Exer

       0   2   4       0   0   7]

Then, factors of A are L and U, that is: A = L*U

The decomposition of the matrix A is an illustration of an important and well known theorem. If A is a nonsingular matrix that can be transformed into an upper diagonal form U by the application or row addition operations, then there exists a lower triangular matrix L such that A = LU.

Row addition operations can be represented by a product of elementary matrices. If n such operations are required, the matrix U is related to the matrix A in the following way:

U = En En-1 ... E2 E1 A

The lower triangular matrix L is found from

L = E1-1 E2

-1 ... En-1

L will have ones on the diagonal. The off-diagonal elements are zeros above the diagonal, while the elements below the diagonal are the multipliers required to perform Gaussian elimination on the matrix A. The element lij

is equal to the multiplier used to eliminate the (i, j) position.

Example:

In Matlab, let's find the LU decomposition of the matrix

A = [-2 1 -3; 6 -1 8; 8 3 -7]

Write this instruction in the command window or within a script:

[L, U] = lu(A)

And the Matlab answer is:

L =   -0.2500   -0.5385    1.0000    0.7500     1.0000           0    1.0000            0           0

Page 84: Matlab Exer

U =    8.0000    3.0000   -7.0000         0     -3.2500   13.2500         0         0         2.3846

We can test the answer, by typing

L*U

And, finnally, the Matlab answer is:

ans =   -2.0000    1.0000   -3.0000    6.0000   -1.0000    8.0000    8.0000    3.0000   -7.0000

>>

Showing that A = L*U, indeed.

Singular Value Decomposition (SVD)Let's suppose that a matrix A is singular. Then, let A be a real m x n matrix of rank r, with m greater than or equal to n. The Singular Value Decomposition (svd) of A is

A = U S V'

(the apostrophe after a matrix or vector means its transpose) where U is an orthogonal m x n matrix, S is an r x r diagonal matrix, and V is an n x n square orthogonal matrix.

Since U and V are orthogonal, then

UU' = I and VV' = I

That is, the transpose of each matrix is equal to its inverse. The elements along the diagonal of S, labelled , are called the singular values of A. There are r such singular values and they satisfy 

If the matrix A is square, then we can use the singular value decomposition to find the inverse, which is is

Page 85: Matlab Exer

A-1 = (USV')-1 = (V')-1S-1U-1 = VS-1U'

since (AB)-1 = B-1A-1, UU' = I, and VV' = I. 

If A is a square matrix then

And so,

If an SVD of a matrix A can be calculated, so can be its inverse. Therefore, we can find a solution to a system

 Ax = b   x = A-1b = VS-1U'b

that would otherwise be usolvable.

Example:

Let's find with Matlab the singular value decomposition of

A = [ 0   -1     -2    1      1    0]

We simply type:

[U,S,V] = svd(A)

and the above operation produces a diagonal matrix S, of the same dimension as A and with nonnegative diagonal elements in decreasing order, and unitary matrices U and V so that A = U*S*V'.

The Matlab answer is:

Page 86: Matlab Exer

U =   -0.1826   -0.8944    0.4082    0.9129    0.0000    0.4082   -0.3651    0.4472    0.8165

S =    2.4495         0         0    1.0000         0         0

V =   -0.8944    0.4472    0.4472    0.8944

>>

 We can confirm the values of UU', VV' and USV, by executing these instructions in Matlab

U*U'V*V'U*S*V

The confirming responses are:

 ans =    1.0000   -0.0000   -0.0000   -0.0000    1.0000   -0.0000   -0.0000   -0.0000    1.0000

ans =     1     0     0     1

ans =   -0.0000   -1.0000   -2.0000    1.0000    1.0000    0.0000

MATLAB Plot - 2D graphics

2D Plots - Fancy Graphic ToolMatlab includes fancy tools for visualization. Basic 2D plots, good 3D graphics, and even animation

possibilities are available in an easy environment.

Page 87: Matlab Exer

The most basic and useful command for producing simple 2D plots is:

plot(xvalues, yvalues, 'style')

xvalues is the value of the horizontal points to be plotted. yvalues is the value of the function to be plotted.  xvalues and yvalues have to have the same length. 'style' is an optional argument that specifies the color, line style and point-marker style.

Examples:

plot(x,y) plots y vs x with a solid lineplot(x,y,'-.') plots y vs x with a dash-dot lineplot(x) plots the elements of x against their own indexplot(x,y,'r--') plots y vs x with a red dashed lineplot(a,b,'k+') plots b vs a with black plus signs

You may annotate your plots with 'xlabel', 'ylabel' and 'title'. Other useful functions are 'legend', 'axis', 'grid' and 'hold'.

Here's an example that integrates all of the above functions.

% Clears variables, command window, and closes all figuresclear, clc,close all

% Defines value of x and two functionsx = 0: .1 : 2*pi;y1 = cos(x);y2 = sin(x);

% Plots two functions with different style, and wider linesplot(x,y1,'b', x, y2, 'r-.', 'linewidth', 2)

% Activates the gridgrid on

% Defines limits for x and y axes, and sets title, labels and legendsaxis([0 2*pi -1.5 1.5])title('2D plots', 'fontsize', 12)xlabel('angle')ylabel('f1(x), f2(x)')legend('cos(x)', 'sin(x)')

Page 88: Matlab Exer

% Keeps figure on screen, in order to add a third functionhold on

% Defines another functiony3 = 0.5 * x;

% Plots over the previous figureplot(x, y3, 'm')

And the result is:

Matlab Plotting - Horizontal Lines and Vertical linesWe are going to create a simple Matlab function to add horizontal lines (and vertical ones) to any given Matlab-created plot.

For example, let's say that we need to add some indications or annotations to a plot, and we need to display and indicate some upper or lower limits.

The proposed Matlab function will have 5 input parameters:

Initial value (where the horizontal line will start) Final value (where the line will end) Y value (vertical position of the line with respect to the plot) Direction (to indicate the direction of the annotation: 1 going upwards, or -1 going

downwards, like an arrow) Vertical range (to display aesthetically proportioned lines)

Page 89: Matlab Exer

We plan the usage of our function like this (its name will be 'plot_limit'):

Usage:    L = [L_min L_max y d r];             plot_limit(L);

where            L_min = starting point           L_max = ending point           y = y value of horizontal line           d = direction (1 or -1)           r = y range

So, we need to know in advance where we want to put our line (sure!).

We define our horizontal and vertical values. We arbitrarily define 300 horizontal points and use a linewidth = 1.5. The instruction 'hold on' keeps the current figure, instead of overwriting it. This Matlab code displays just a horizontal line.

a = linspace(L_min, L_max, 300);b = linspace(y, y, 300);plot(a,b,'k-','linewidth',1.5)hold on

Then, we add some tiny vertical lines on each side of the horizontal one. If direction 'd' is 1, the vertical lines are below the horizontal line (going 'up'). If direction 'd' is -1, the vertical lines are above the horizontal one (going 'down'). We take the vertical range into account, in 'r', to display a vertical line of just 3% of the total 'height' of the current figure. You can try different values to suit your needs, obviously. We find the initial or final points of the vertical lines with an 'if-statement'.

This is the code to achieve it.

% Initial vertical linea = linspace(L_min, L_min, 10);if d == 1    b = linspace(y-r*.03, y, 10);else    b = linspace(y, y+r*.03, 10);endplot(a,b,'k-','linewidth',1.5)hold on

% Final vertical linea = linspace(L_max, L_max, 10);if d == 1    b = linspace(y-r*.03, y, 10);

Page 90: Matlab Exer

else    b = linspace(y, y+r*.03, 10);endplot(a,b,'k-','linewidth',1.5)

Now, we'll test our function with this script.

clear; clc; close all

x = 0 : 2*pi/360 : 2*pi;y = sin(x);

plot(x,y)grid on xlabel('angle')ylabel('sin(x)')title('Plot showing horizontal and vertical lines')hold onplot_limit([0.8, 2.5, 0.4, 1, 2])plot_limit([4, 5.4, -0.6, -1, 2])

The result is:

The first line starts at 0.8, ends at 2.5, and has a vertical value of 0.4. The vertical lines simulate an up-arrow (d = 1).

Page 91: Matlab Exer

The second line starts at 4, ends at 5.4, and has a vertical value of -0.6. Direction goes down (d = -1).

Pie Plots - figures in Matlab

pie(x) draws pie plots of the data in the vector x. The values in x are normalized via x/sum(x) to determine the area of each slice of pie.

If sum(x) is less or equal to 1, the values in x directly specify the area of the pie slices. Only a partial pie will be drawn if sum(x) is less than < 1.

The '%' sign indicates that there is a comment in that line and Matlab does not do anything with it. It is as if it were inexistent, and it exists only for explanatory purposes.

Example:

% Clears variables, command window, and closes all figuresclc; clear; close all

% These are the names of the slicesnames = char('Region 1', 'Region 2', 'Distr. 3', 'Distr. 4');

% These are the numbers to be plotteddata = [1200, 500, 300, 120];pie(data)

% gtext('string') displays the graph window, puts up a% cross-hair, and waits for a mouse button or keyboard % key to be pressed.for i=1:4 gtext(names(i,:));endtitle('Sales', 'fontsize', 15)

The result is:

Page 92: Matlab Exer

hist - Histograms in MatlabCommands for histograms and vertical data

The hist instruction in Matlab, without output arguments, produces a histogram bar plot of the results.

The bar edges on the first and last bins may extend to cover the min and max of the data unless a matrix of data is supplied.

A histogram is a graphical representation used to estimate the probability distribution of a variable. It counts the frequencies  of data into discrete intervals (bins), and then plots a rectangle over each interval.

Example 1:

This Matlab code creates a histogram with 3 bars. The first bar has two '1' values, the second bar has three '2' values, and the third bar has one '3' values.

y = [1 1 2 2 2 3]hist(y)

Page 93: Matlab Exer

The horizontal axis has the different values in the vector to be plotted.The vertical axis has the number of those values in the vector.

Example 2:

This Matlab code generates a histogram of 15 randomly distributed numbers between 0 and 1 (you can type 'help rand' on your command window to learn about random numbers).

a = randn(15,1)hist(a)

a =   -0.8468   -0.2463    0.6630   -0.8542   -1.2013   -0.1199   -0.0653    0.4853   -0.5955   -0.1497   -0.4348   -0.0793    1.5352   -0.6065   -1.3474

>>

Page 94: Matlab Exer

Note that each column includes a range of values, otherwise the histogram would contain 15 bars.

Matlab Plot - stemIn this example, we study the 'stem' instruction to plot Matlab functions.

It draws vertical lines (with a little circle at the tip) proportional to the value of the function at that particular horizontal value. 'stem' does not join the circles with a line, and it is very helpful to stress the fact that the function is not continuous but discrete.

Let's assume that we want to plot the following elegant exponential and sinusoidal function:

Example: let's draw a simple discrete function

We can develop a script like this:

% Avoid superimposed operations and close previous figs.clc; clear; close all 

% First, we define 51 values of our independent variablex = 0 : 2*pi/50 : 2*pi; 

% Second, we define the function to graphy = exp(-x/3) .* sin(x); 

Page 95: Matlab Exer

% Third, we use the 'stem' function to plot discrete valuesstem(x,y) 

% We can add title and labels (as strings in arguments)title('Demonstration of the -stem- function')xlabel('angle x')ylabel('f(x)')

And we get the following plot:

If we define our independant variable using less points, as in

x = 0 : 2*pi/20 : 2*pi;

we get the following visual change:

Page 96: Matlab Exer

loglog - logarithmic plot

In this example we are going to demonstrate how to use the 'loglog' function included in Matlab to produce non-linear plots.

This term referrs to the fact that the plot is logarithmically scaled in both axes. There are other functions such as 'semilogx' and 'semilogy' which have one axis in linear scale and the other axis in logarithmic scale.

Example of a logarithmic graphic:

clear; clc; close all 

% Define your independent variablet = 0 : 2*pi/360 : 2*pi; 

% Define values along your x-axisx = exp(t);% Define values along your y-axisy = 50 + exp(3*t); 

% Plot your function with a wider line and grid the figureloglog(x, y, 'LineWidth', 2)grid 

Page 97: Matlab Exer

% Use a title for the figuretitle('Demonstration of logarithmic plots') 

% Label your x-axis with a double line.% Note the special charactersxlabel([{'e^{t}'}; {'0 \leq t \leq 2\pi'}]) 

% Label your y-axisylabel('50 + e^{3t}')

The produced figure is:

Polar Plots (with a little help from Matlab)Matlab provides functions that produce polar plots in appropriate coordinates using magnitudes and

angles.

In this article we’ll discuss and show the Matlab built-in commands 'compass', 'polar' and 'rose'.

The polar coordinate system is a two-dimensional system in which each point on a plane is determined by a distance from a fixed point and an angle from a fixed axis.

Page 98: Matlab Exer

The Compass Function 

The compass function takes its inputs in Cartesian format, but outputs polar plots. In the compass function each arrow’s length corresponds to the magnitude of a data element and its pointing direction indicates the angle of the complex data. This function creates arrows that go out from the origin of the axes in a polar coordinate system. To illustrate this function, we’ll create a set of arrows that increase in size from arrow to arrow in a counter-clockwise manner.

t = 1 : 5;r = t .* exp(i * t * 36 * (pi/180));compass(r)

This code produces:

The Polar Function

The polar function creates polar plots from angle and magnitude data.

It takes the forms polar(theta,rho), where theta corresponds to the angle (in radians) and rho corresponds to the magnitude. The variables theta and rho must be identically sized vectors.

As an example, we create a cardioid with the following code:

Page 99: Matlab Exer

t = 0 : 2*pi/100 : 2*pi;r = 1 - sin(t);polar(t, r)

Here’s the result:

Here’s another polar chart:

t = 0 : 2*pi/100 : 2*pi;r = sqrt(abs(sin(3*t)));polar(t,r)

Page 100: Matlab Exer

The Rose Function

With rose you can create angle histograms that are drawn in polar coordinates. By using rose(angle_data), the function will determine how many of the angles (in radians) fall within a given angular bin. By default there are 20 evenly spaced bins between 0 and 2pi. The number of bins can be changed by using rose(angle_vector, nr_of_bins), where the variable nr_of_bins is a scalar specifying the number of bins that should be spaced between 0 and 2pi. You can also specify the centers of the bins by passing a vector, bin_centers, to the rose function, like this: rose(angle_vector, bin_centers).

The following code produces a rose plot of data which is normally distributed in angle about 90º.

angle_vector = angle(exp(i*randn(1, 500))) + pi/2;rose(angle_vector)

This is the result of the angle histogram created with rose:

Gaussian distribution – how to plot it in MatlabIn statistics and probability theory, the Gaussian distribution is a continuous distribution that gives a good description of data that cluster around a mean. The graph or plot of the associated probability density has a peak at the mean, and is known as the Gaussian function or bell curve.

The Probability Density Function (PDF) in this case can be defined as:

Page 101: Matlab Exer

where 

The formula above can me coded in Matlab easily, like this: 

function f = gauss_distribution(x, mu, s)p1 = -.5 * ((x - mu)/s) .^ 2;p2 = (s * sqrt(2*pi));f = exp(p1) ./ p2; 

Now, let’s use it in an example. 

We produce 500 random numbers between -100 and 100, with mean m = 0 and standard deviation s = 30. The code is: 

a = -100; b = 100;x = a + (b-a) * rand(1, 500);m = (a + b)/2;s = 30; 

Then, we plot this information using our bell curve: 

f = gauss_distribution(x, m, s);plot(x,f,'.')grid ontitle('Bell Curve')xlabel('Randomly produced numbers')ylabel('Gauss Distribution') 

The produced shape is:

Page 102: Matlab Exer

 

An important property of this bell-shaped curve is that the values less than one standard deviation from the mean (between green lines below) represent approximately 68.2% of the area under the curve, while two standard deviations from the mean (between red lines below) take about 95.4%, and three standard deviations account for about 99.7% of the area.

 

Simple Animation in Matlab

Page 103: Matlab Exer

If we have some data representing a system or a function at several time intervals, we may want to take advantage of Matlab’s simple animation capabilities.  We're going to expose the basic method or algorithm for animations.

In this example we’re going to work with just three special instructions.

The idea is to store every figure as a frame of the ‘movie’, with each frame stored as a column vector of a matrix, an then play all the frames on the screen.

moviein(nr_frames): we initialize the matrix that will keep the frames, with the number of frames to be generated. 

getframe: with this instruction we keep the information of a given figure and ‘load’ a temporary matrix with information. 

movie(matrix, times, FPS): this is used to play the movie after its generation. Parameter ‘matrix’ is the saved data, ‘times’ the number of times that the movie will be played back, and ‘FPS’ means ‘frames per second’ (the default is 12). 

Let’s try this simple animation example: 

% Define number of framesnr_fr = 10;% Initialize matrix using 'moviein'frames = moviein(nr_fr); 

% Generate frames with any plotting function. % We use a cosine with variable frequency.t = 0 : .01 : 6;f = 1;for i = 1 : nr_fr    f = f * 1.25; w = 2 * pi * f;    y = cos(w*t);    plot(t, y);    title('Recording movie...')    % Get every frame with 'getframe' and load the appropriate   % matrix.    frames(:, i) = getframe;end

% Save the matrix so that this movie can be loaded latersave frames 

This is the first frame of the recording:

Page 104: Matlab Exer

Now you can play back the movie: 

% Play the movie once, 2 FPS.title('Movie being played back...')movie(frames, 1, 2) 

This is the last frame of the animation:

Done!

Page 105: Matlab Exer

Comet Plotcomet(a) displays an animated comet plot of the vector a.comet(a, b) displays an animated comet plot of vector b vs. a.comet(a, b, p) uses a comet of length p*length(b). Default is p = 0.10.

Example:

If you want to plot the following function:

, for the range , you can write this script in Matlab:

% Clears variables, command window, and closes all figuresclc; clear; close all

% Generates 300 linearly spaced points from 0 to 8*pix = linspace(0, 8*pi, 300);

% Creates the formula to be plotted% (it's a multiplication between vector 'x' and vector 'cos(x)')y = x .* cos(x);

% Plot it!comet(x, y, .6)

An the result is...

Page 106: Matlab Exer

It is much better to see it on your own screen, because it moves like a ribbon!

You can experiment with different p values to see the length of the comet changing...

3D Plot - (Graphic Tools)Computer graphics are better for understanding  many types of data

In these sections you can find many step-by-step commented guides to easily develop 3D plots. If you are not familiar with tridimensional graphics in Matlab, I recommend you start from Part 1; otherwise, go to the link of your interest.

Matlab provides many powerful instructions for the visualization of 3D data.

The instructions provided include tools to plot wire-frame objects, 3D plots, curves, surfaces...

... and can automatically generate contours, display volumetric data, interpolate shading colors and even display non-Matlab made images. Here are some commonly used functions (there are many more):

plot3 stem3 pie3 comet3 contour3 mesh meshc surf

Page 107: Matlab Exer

surfc sphere ellipsoid cylinder

Among these instructions, plot3 and comet3 are the 3D matches of plot and comet commands mentioned in the 2D plot section.

The general syntax for the plot3 command is plot3(x, y, z, 'style')

This command draws a 3D curve with the specified line style. The argument list can be repeated to make overlay plots, just the same way as with the plot command in 2D.

We have to make some necessary comments before any example can be introduced.

Plots in 3D may be annotated with instructions already mentioned for 2D plots: xlabel, ylabel, title, legend, grid, etc., plus the addition of zlabel. The grid command in 3D makes the appearance of the plots better, especially for curves in space.

ViewThe viewing angle of the observer is specified by the command view(azimuth, elevation), where

azimuth (in degrees): specifies the horizontal rotation from the y-axis, measured positive counterclockwise (default value is -37.5 degrees).

elevation (in degrees): specifies the vertical angle measured positive above the xy-plane (default value is 30 degrees).

Page 108: Matlab Exer

By specifying appropriate values of azimuth and elevation, one can plot projections of 3D objects on different 2D planes. For example, the command 'view(90,0)' places the viewer toward the positive x-axis, looking straigth on the yz-plane, and thus produces a 2D projection of the object on the yz-plane. 'view(0, 90)' shows the figure on a 2D xy-plane.

The following script generates data, plots the curves and obtains different views.

Example:

% clears variables, command window and closes all previous figuresclear; clc; close all

% generates an angle vector with 101 valuesa = 0: 3*pi/100 : 3*pi;

% calculates x, y, and zx = cos(a);y = sin(a);z = a;

% divides the figure window into 4 subwindows (2x2)% plots on the 1st. onesubplot(2,2,1)plot3(x,y,z)grid ontitle('A helix - 3D view')xlabel('x = cos(a)')ylabel('y = sin(a)')zlabel('z = a')

% plots on the 2nd. subwindowsubplot(2,2,2)plot3(x,y,z)axis('square')% rotates the figure to show only the xy-planeview(0,90)grid ontitle('A helix, xy-plane')

Page 109: Matlab Exer

xlabel('x = cos(a)')ylabel('y = sin(a)')zlabel('z = a')

% plots on the 3rd. subwindowsubplot(2,2,3)plot3(x,y,z)% rotates the figure to show only the xz-planeview(0,0)grid ontitle('A helix, xz-plane')xlabel('x = cos(a)')ylabel('y = sin(a)')zlabel('z = a')

% plots on the 4th. subwindowsubplot(2,2,4)plot3(x,y,z)% rotates the figure to show only the yz-planeview(-90,0)grid ontitle('A helix, yz-plane')xlabel('x = cos(a)')ylabel('y = sin(a)')zlabel('z = a')

And the result is:

Page 110: Matlab Exer