• No results found

Bible of Matlab

N/A
N/A
Protected

Academic year: 2021

Share "Bible of Matlab"

Copied!
235
0
0

Loading.... (view fulltext now)

Full text

(1)

Tutorial Lesson: Using MATLAB (a

minimum session)

You'll log on or invoke MATLAB, do a few trivial calculations and log off.

Launch MATLAB. You can start it from your Start Menu, as any other Windows-based program. You see now something similar to this Figure:

The History Window is where you see all the already typed commands. You can scroll through this list.

The Workspace Window is where you can see the current variables.

The Comand Window is your main action window. You can type your commands here.

At the top of the window, you can see your current directory. You can change it to start a new project.

Once the command window is on screen, you are ready to carry out this first lesson. Some commands and their output are shown below.

Enter 5+2 and hit the enter key. Note that the result of an unassigned expression is saved in the default variable 'ans'.

>> 5+2 ans =

(2)

7 >>

The '>>' sign means that MATLAB is ready and waiting for your input. You can also assign the value of an expression to a variable.

>> z=4 z = 4 >>

A semicolon (at the end of your command) suppresses screen output for that instruction. MATLAB remembers your variables, though. You can recall the value of x by simply typing x >> x=4; >> x x = 4 >>

MATLAB knows trigonometry. Here is the cosine of 6 (default angles are in radians).

>> a=cos(6) a =

0.9602 >>

The floating point output display is controlled by the 'format' command. Here are two examples.

>> format long >> a

a =

(3)

>> format short >> a a = 0.9602 >> Well done!

Close MATLAB (log off).

You can also quit by selecting 'Exit MATLAB' from the file menu.

Tutorial Lesson: Vector Algebra

(Algebra with many numbers, all at

once...)

You'll learn to create arrays and vectors, and how to perform algebra and trigonometric operations on them. This is called Vector Algebra.

An array is an arbitrary list of numbers or expressions arranged in horizontal

rows and vertical columns. When an array has only one row or column, it is called

a vector. An array with m rows and n columns is a called a matrix of size m x n. Launch MATLAB and reproduce the following information. You type only what you see right after the '>>' sign. MATLAB confirms what you enter, or gives an answer. Let x be a row vector with 3 elements (spaces determine different columns). Start your vectors with '[' and end them with ']'.

>> x=[3 4 5] x =

3 4 5 >>

Let y be a column vector with 3 elements (use the ';' sign to separate each row). MATLAB confirms this column vector.

>> y=[3; 4; 5] y =

3 4 5

(4)

>>

You can add or subtract vectors of the same size: >> x+x ans = 6 8 10 >> y+y ans = 6 8 10 >>

You cannot add/subtract a row to/from a column (Matlab indicates the error). For example:

>> x+y

??? Error using ==> plus Matrix dimensions must agree.

You can multiply or divide element-by-element of same-sized vectors

(using the '.*' or './' operators) and assign the result to a different variable vector: >> x.*x ans = 9 16 25 >> y./y ans = 1 1 1 >> a=[1 2 3].*x a = 3 8 15 >> b=x./[7 6 5] b =

(5)

0.4286 0.6667 1.0000 >>

Multiplying (or dividing) a vector with (or by) a scalar does not need any special operator (you can use just '*' or '/'):

>> c=3*x c = 9 12 15 >> d=y/2 d = 1.5000 2.0000 2.5000 >>

The instruction 'linspace' creates a vector with some elements linearly spaced between your initial and final specified numbers, for example:

r = linspace(initial_number, final_number, number_of_elements) >> r=linspace(2,6,5) r = 2 3 4 5 6 >> or >> r=linspace(2,3,4) r = 2.0000 2.3333 2.6667 3.0000 >>

Trigonometric functions (sin, cos, tan...) and math functions (sqrt, log, exp...)

operate on vectors element-by-element (angles are in radians). >> sqrt(r)

(6)

1.4142 1.5275 1.6330 1.7321 >> cos(r) ans = -0.4161 -0.6908 -0.8893 -0.9900 >> Well done! So far, so good?

Experimenting with numbers, vectors and matrices is good for you and it does not hurt!

Go on!

Tutorial Lesson: a Matlab Plot

(creating and printing figures)

You'll learn to make simple MATLAB plots and print them out.

This lesson teaches you the most basic graphic commands.

If you end an instruction with ';', you will not see the output for that instruction. MATLAB keeps the resuls in memory until you let the results out.

Follow this example, step-by-step.

In the command window, you first create a variable named 'angle' and assign 360 values, from 0 to 2*pi (the constant 'pi' is already defined in MATLAB):

>> angle = linspace(0,2*pi,360);

Now, create appropriate horizontal and vertical values for those angles: >> x=cos(angle);

>> y=sin(angle);

Then, draw those (x,y) created coordinates: >> plot(x,y)

Set the scales of the two axes to be the same: >> axis('equal')

Put a title on the figure: >> title('Pretty Circle')

(7)

>> ylabel('y') >> xlabel('x')

Gridding the plot is always optional but valuable:

>> grid on

You now see the figure:

The 'print' command sends the current plot to the printer connected to your computer:

>> print

The arguments of the axis, title, xlabel, and ylabel commands are text strings. Text strings are entered within single quotes (').

Do you like your plot? Interesting and funny, isn't it?

Tutorial Lesson: Matlab Code

(Creating, Saving, and Executing a

Script File)

You'll learn to create Script files (MATLAB code) and execute them.

A Script File is a user-created file with a sequence of MATLAB commands in it. You're actually creating MATLAB code, here. The file must be saved with a '.m' extension, thereby, making it an m-file.

The code is executed by typing its file name (without the '.m' extension') at the

(8)

Now you'll write a script file to draw the unit circle of Tutorial Lesson 3.

You are esentially going to write the same commands in a file, save it, name it, and execute it within MATLAB.

Follow these directions:

Create a new file. On PCs, select 'New' -> 'M-File' from the File menu, or use the related icons.

A new edit window appears.

Type the following lines into this window. Lines starting with a '%' sign are

interpreted as comments and are ignored by MATLAB, but are very useful for you, because then you can explain the meaning of the instructions.

% CIRCLE - A script file to draw a pretty circle

angle = linspace(0, 2*pi, 360); x = cos(angle); y = sin(angle); plot(x,y) axis('equal') ylabel('y') xlabel('x') title('Pretty Circle') grid on

Write and save the file under the name 'prettycircle.m'.

On PCs select 'Save As...' from the File menu. A dialog box appears. Type the name of the document as prettycircle.m. Make sure the file is being saved in the folder you want it to be in (the current working folder / directory of MATLAB).

Click on the 'Save' icon to save the file.

Now go back to the MATLAB command window and type the following command to execute the script file.

>>prettycircle

(9)

And you achieve the same 2D plot that you achieved in Tutorial Lesson 3, but the difference is that you saved all the instructions in a file that can be accessed and run by other m-files! It's like having a custom-made code!

You're doing great!

Tutorial Lesson: Matlab Programs

(create and execute Function Files)

You'll learn to write and execute Matlab programs. Also, you'll learn the difference between a script file and a function file.

A function file is also an M-file, just like a script file, but it has a

function definition line on the top, that defines the input and output explicitly. You are about to create a MATLAB program!

You'll write a function file to draw a circle of a specified radius, with the radius being the input of the function. You can either write the function file from scratch or modify the script file of this Tutorial Lesson.

Open the script file prettycircle.m (created and saved before).

On PCs, select 'Open' -> 'M-File' from the File menu. Make sure you're in the correct directory.

Navigate and select the file prettycircle.m from the 'Open' dialog box. Double click to open the file. The contents of the program should appear in an edit window. Edit the file prettycircle.m from Tutorial 4 to look like the following:

function [x, y] = prettycirclefn(r)

% CIRCLE - A script file to draw a pretty circle % Input: r = specified radius

(10)

% Output: [x, y] = the x and y coordinates

angle = linspace(0, 2*pi, 360); x = r * cos(angle); y = r * sin(angle); plot(x,y) axis('equal') ylabel('y') xlabel('x') title(['Radius r =',num2str(r)]) grid on

Now, write and save the file under the name prettycirclefn.m as follows: On PCs, select 'Save As...' from the 'File' menu. A dialog box appears.

Type the name of the document as prettycirclefn. Make sure the file is saved in the folder you want (the current working folder/directory of MATLAB). Click on the 'Save' icon to save the file.

In the command window write the following: >> prettycirclefn(5);

and you get the following figure (see the title):

Then, try the following: >> radius=3;

>> prettycirclefn(radius); >>

and now you get a circle with radius = 3

(11)

function [x, y] = prettycirclefn(r), where you define the input variables and the

output ones.

The argument of the 'title' command in this function file is a combination of

a fixed part that never changes (the string 'Radius r= '), and a variable part that depends on the argumments passed on to the function, and that converts a number into a string (instruction 'num2str').

You can generate now a circle with an arbitrary radius, and that radius can be assigned to a variable that is used by your MATLAB program or function!

Great!

Polynomials

Polynomials are used so commonly in algebra, geometry and math in general that Matlab

has special commands to deal with them. The polynomial 2x

4

+ 3x

3

− 10x

2

− 11x + 22 is

represented in Matlab by the array [2, 3, -10, -11, 22] (coefficients of the polynomial

starting with the highest power and ending with the constant term). If any power is

missing from the polynomial its coefficient must appear in the array as a zero.

Here are some examples of the things that Matlab can do with polynomials. I suggest you

experiment with the code…

Roots of a Polynomial

% Find roots of polynomial p = [1, 2, -13, -14, 24]; r = roots(p)

% Plot the same polynomial (range -5 to 5) to see its roots x = -5 : 0.1 : 5;

f = polyval(p,x); plot(x,f)

grid on

Find the polynomial from the roots

If you know that the roots of a polynomial are -4, 3, -2, and 1, then you can find the

polynomial (coefficients) this way:

r = [-4 3 -2 1]; p = poly(r)

(12)

Multiply Polynomials

The command conv multiplies two polynomial coefficient arrays and returns the

coefficient array of their product:

a = [1 2 1]; b = [2 -2]; c = conv(a,b)

Look (and try) carefully this result and make sure it’s correct.

Divide Polynomials

Matlab can do it with the command deconv, giving you the quotient and the remainder

(as in synthetic division). For example:

% a = 2x^3 + 2x^2 - 2x - 2 % b = 2x - 2

a = [2 2 -2 -2]; b = [2 -2];

% now divide b into a finding the quotient and remainder [q, r] = deconv(a,b)

You find quotient q = [1 2 1] (q = x

2

+ 2x + 1), and remainder r = [0 0 0 0] (r = 0),

meaning that the division is exact, as expected from the example in the multiplication

section…

First Derivative

Matlab can take a polynomial array and return the array of its derivative:

a = [2 2 -2 -2]

(meaning a = 2x

3

+ 2x

2

- 2x - 2)

ap = polyder(a)

The result is ap = [6 4 -2] (meaning ap = 6x

2

+ 4x - 2)

(13)

If you have some data in the form of arrays (x, y), Matlab can do a least-squares fit of a

polynomial of any order you choose to this data. In this example we will let the data be

the cosine function between 0 and pi (in 0.01 steps) and we’ll fit a polynomial of order 4

to it. Then we’ll plot the two functions on the same figure to see how good we’re doing.

clear; clc; close all

x = 0 : 0.01 : pi;

% make a cosine function with 2% random error on it f = cos(x) + 0.02 * rand(1, length(x));

% fit to the data p = polyfit(x, f, 4); % evaluate the fit g = polyval(p,x);

% plot data and fit together plot(x, f,'r:', x, g,'b-.') legend('noisy data', 'fit') grid on

Got it?

Examples: Basic Matlab Codes

Here you can find examples on different types of arithmetic, exponential, trigonometry and complex number operations handled easily with MATLAB codes.

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

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

7.3529 >>

(14)

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 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

(15)

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

Examples: Simple Vector Algebra

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.

(16)

y = x .* w;

You can create an array (or matrix) by combining two or more vectors: 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)+3 m(2,4) = 0 m(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 >>

(17)

MATLAB automatically presents a coefficient before the matrix, to simplify the

notation. In this case .

Examples: MATLAB Plots

In this group of examples, we are going to create several MATLAB plots. 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 values

x = 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:

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:

(18)

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 values

x = linspace(0, 4*pi, 100); y = cos(x); plot(x,y, 'ro') xlabel('x (radians)') ylabel('cos(x)') title('Plotting a cosine') grid on 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:

(19)

% Another way to assign values to a vector

t = 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 figure

clc; clear; close all

% CIRCLE - A script file to draw a pretty circle

% We first generate a 90-element vector to be used as an angle

angle = linspace(0, 2*pi, 90);

% Then, we create another 90-element vector containing only value 2

r2 = linspace(2, 2, 90);

% Next, we plot a red circle using the 'polar' function

polar(angle, r2, 'ro') title('One more Circle')

(20)

% We avoid deletion of the figure

hold on

% Now, we create another 90-element vector for radius 1

r1 = linspace(1, 1, 90); polar(angle, r1, 'bx')

% Finaly, we mark the center with a black square

polar(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:

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.

(21)

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 >> [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 manipulation

In this page 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.

(22)

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: 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:

(23)

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: 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 ==> mtimes

Inner matrix dimensions must agree.

(24)

g = [a b c] h = [c' a' b']' Matlab produces: g = 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)]

And Matlab produces: j =

(25)

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:

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

(26)

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 = 2

b = 2.0000 c = 2

Note that the angle has to be expressed in radians, and that the instruction

'norm(vector, 2)' 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

In this example, we are going to write a function to find the cross product of two given vectors u and v.

(27)

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 figures

clc; close all; clear

% Supress empty lines in the output

format compact

% Define unit vectors

i = [1 0 0]; j = [0 1 0]; k = [0 0 1];

% Call the previously created function

w1 = crossprod(i,j) w2 = crossprod(i,k)

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

w4 = cross(i,k)

And Matlab displays: w1 =

0 0 1 w2 =

0 -1 0

*** compare with results by Matlab *** w3 =

0 0 1 w4 =

(28)

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:

(a+bi) + (c-di) = (a+c)+(b-d)i In Matlab, it's very easy to do it: >> a = 3-5i a = 3.0000 - 5.0000i >> b = -9+3i b = -9.0000 + 3.0000i >> a + b ans = -6.0000 - 2.0000i >> a - b ans = 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*b

ans =

(29)

>> a/b ans =

-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.

To plot numbers (3+2i), (-2+5i) and (-1-1i), we can write the following code in Matlab:

% 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 plot

xlabel('x (real axis)') ylabel('y (imaginary axis)')

% Activate the grid

grid on

And you get:

(30)

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 is called theangle

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-4i magnitude = abs(a) ang = angle(a) a = 3.0000 - 4.0000i magnitude = 5 ang = -0.9273

De Moivre's Theorem

The nth power of is

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

.

(31)

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.

Future Value

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.

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 years

p = initial investment

i = nominal interest rate

n = number of compounding period 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.

(32)

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

function

[ii, nir, ncppy, ny] = enter_values

ii = 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 decimal

ni = nir / (100 * ncppy);

% Calculate future value by formula

t = ii*(1 + ni)^(ncppy * ny);

% Round off to nearest cent

t = floor(t * 100 + 0.5)/100;

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

% Instruction ‘format bank’ delivers fixed format for dollars and cents

% Instruction ‘format compact’ suppresses extra line-feeds

clear; clc; format compact

format bank

[ii, nir, ncppy, ny] = enter_values;

t = future_value(ii, nir, ncppy, ny)

This is a sample run:

Enter initial investment: 6800

Enter nominal interest rate: 9.5

Enter number of compounding periods per year: 4

Enter number of years: 10

with the result:

t =

(33)

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

iteration (for loop)

The MATLAB iteration structure (for loop) repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. The general format is:

for variable = expression

statement ...

end Example:

c = 5;

% Preallocate matrix, fill it with zeros a = zeros(c, c); for m = 1 : c for n = 1 : c a(m, n) = 1/(m + n * 5); end end a

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

(34)

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 Multiplication

If 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, 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 figures

clc; close all; clear

% Avoid empty lines

format compact

% Define matrices, for example these

A = [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 size

if c1 ~= r2

disp ('*** not able to multiply matrices ***') end

% Main code

% Vary each row of matrix A

for i = 1 : r1

% Vary each column of matrix B

(35)

% 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 end

end

% Compare our result with a multiplication by Matlab

A*B

Matlab displays the following results: A = 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

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.

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

Control Structures (while statement

loop)

Among the control structures, there is the while... end loop which repeats a group of statements an indefinite number of times under control of a logical condition.

(36)

Syntax: while expression statements ... end Example: counter = 100; while (counter > 95)

disp ('counter is still > 95') counter = counter -1;

end

disp('counter is no longer > 95')

Matlab response is: counter is still > 95 counter is still > 95 counter is still > 95 counter is still > 95 counter is still > 95 counter is no longer > 95 >>

The cautions involving matrix comparisons that are discussed in the section on the if

statement also apply to the while statement.

if statement

The 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. The groups of statements are delineated by the four keywords (no braces or brackets are involved).

The general form of the statement is:

if expression1

(37)

... elseif expression2 statements2 ... else statements3 ... end

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 the

isequal 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:

(38)

isequal isempty all any

break statement

The break statement lets you exit early from a for or while loop. In nested

loops, 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;

... end

end

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 method. We start with an arbitrary square matrix and a same-size identity matrix (all the elements along its diagonal are 1).

(39)

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, 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 function

if r ~= c

disp('Only Square Matrices, please') b = [];

return end

% Target identity matrix to be transformed into the output % inverse matrix

b = eye(r);

%The following code actually performs the matrix inversion

for j = 1 : r for i = j : r 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

(40)

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 end end

% 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 matrix

a = [3 5 -1 -4 1 4 -.7 -3 0 -2 0 1 -2 6 0 .3];

% Call the function to find its inverse

b = mat_inv2(a)

% Compare with a result generated by Matlab

c = 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 =

(41)

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 matrix a = [1 1 1 1];

% Call the function to find its inverse

b = mat_inv2(a)

% Compare with a result generated by Matlab

c = inv(a)

And Matlab display is: Warning: Singular Matrix b =

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 Statement

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

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

(42)

...

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 Operator

In 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.

(43)

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

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 Operators

There 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

(44)

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.

Axioms - Laws of Boolean Algebra

Boolean algebra is the algebra of propositions.

Propositions are denoted by letters, such as A, B, x or y, etc.

In the following axioms and theorems (laws of boolean algebra), the '+' or 'V' signs represent a logical OR (or conjunction), the '.' or '^' signs represent a

logical AND (or disjunction), and '¬' or '~' represent a logical NOT ( or negation).

Every proposition has two possible values: 1 (or T) when the proposition is true and

0 (or F) when the proposition is false.

The negation of A is written as ¬A (or ~A) and read as 'not A'. If A is true then ¬A is false. Conversely, if A is false then ¬A is true.

Descript. OR form AND form Other way to express it:

Axiom x+0 = x x.1 = x A ^ T = A A V F = A Commutative x+y = y+x x.y = y.x A V B = B V A

A ^ B = B ^ A

Distributive (x.y)+(x.z) x.(y+z) = (x+y).(x+z) x+y.z = A ^ (B V C) = (A ^ B) V (A ^ C) A V B ^ C = (A V B) ^ (A V C) Axiom x+¬x = 1 x.¬x = 0 A ^ ¬A = F A V ¬A = T

Theorem x+x = x x.x = x A ^ A = A A V A = A Theorem x+1 = 1 x.0 = 0 A V T = T A ^ F = F

Theorem ¬¬x = x ¬(¬A) = A

(45)

Absorption x+x.y = x x.(x+y) = x A V A ^ B = A A ^ (A V B) = A DeMorgan's

laws ¬(¬x.¬y) x+y = ¬(¬x+¬y) x.y = A V B = ¬(¬A ^ ¬B) A ^ B = ¬(¬A V ¬B)

Using logical gates, the commutative property for a logical AND is:

The commutative property for a logical OR, is:

Using electronic gates, the distributive property is:

The De Morgan's laws can transform logical ORs into logical ANDs (negations are necessary) and can electronically be described this way:

Or

De Morgan Laws

In Boolean Algebra, there are some very important laws which are called the De

Morgan's laws (the spelling can change from author to author).

(46)

Using gates (commonly used in Digital Electronics), they can be expressed in two forms:

the OR form:

the AND form:

In Matlab, these laws can be demonstrated very easily. Let's create a script file like this:

% Let x and y be column vectors

x = [0 0 1 1]' y = [0 1 0 1]'

% We can demonstrate the OR form of the law % with these two lines

x_or_y = x|y

DeMorg1 = not(not(x)& not(y))

% We can demonstrate the AND form of the law % with these two lines

x_and_y = x&y

DeMorg2 = not(not(x) | not(y))

When we run it, we get this output: x = 0 0 1 1 y = 0 1 0 1 x_or_y = 0 1 1 1 DeMorg1 = 0 1 1 1 x_and_y = DeMorg2 =

(47)

0 0 0 1 0 0 0 1

Which demonstrates the De Morgan's laws.

Logical AND

A B A & B 0 0 0 0 1 0 1 0 0 1 1 1

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).

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

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

(48)

>>

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: >> x & y ans = 0 1 1 0 0 >>

Logical OR

A B A | B 0 0 0 0 1 1 1 0 1 1 1 1

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).

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.

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:

(49)

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: 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

A B x o r (A,B) 0 0 0

0 1 1 1 0 1 1 1 0

(50)

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 = 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:

(51)

y =

1 2 3 0 0

Then, the logical exclusive OR between x and y is: ans = 1 0 0 1 0 >>

Logical NOT

A ~A 0 1 1 0

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).

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: 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: If vector x is:

(52)

x =

0 1 2 -3 0 Then, the NOT x is produced: >> ~x ans = 1 0 0 0 1 >>

Determinants in Matlab

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,

Thus

. 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

(53)

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 = 16

4x + y = -3

The denominator for both x and y is

.

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.

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

(54)

calculator. Let's see how easy Matlab makes this task.

We'll solve the set of linear equations given below. To solve these equations, no prior

knowledge of matrix algebra or linear methods is required. The first two steps described

below are really basic for most people who know a just little bit of linear algebra.

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

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).

(55)

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:

A*x

And the Matlab answer is:

ans =

15.0000

13.0000

-9.0000

>>

which corresponds to b, indeed.

Cramer's Rule

The 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

(56)

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

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...

(57)

Solve this system using Cramer’s Rule

2x + 4y – 2z = -6

6x + 2y + 2z = 8

2x – 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:

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!

(58)

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

And Matlab response is:

variables =

1.0000

-1.0000

2.0000

Linear Algebra and its Applications

- Circuit Analyisis -

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):

(59)

We can describe the circuit with the following system of linear equations: 7 - 1(i1 - i2) - 6 - 2(i1 - i3) = 0

-1(i2 - i1) - 2(i2) - 3(i2 - i3) = 0 6 - 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 =

References

Related documents

Indeed, the Web survey of 411 risk managers— conducted by the Flaspöhler Research Group, in partnership with National Underwriter—found that 45.8 percent are “very

Capabilities of Portal Single Sign On Personalization Customization Navigation Secure Access IT Perspective People Awareness User Perspective Integration at the glass CRM

These models included TP, ni- trates, agricultural surface, number of inhabitants (excluded in the IBMWP model), IHF, water temperature, mean discharge and altitude as fixed

106 No person other than a Director retiring at the meeting shall, unless recommended by the Directors, be eligible for election to the office of Director at any

The National Qualifications Authority (NQA) has established a national framework of qualifications published in the Qualification Framework Emirates Handbook in 2011 (QF Emirates ),

The first prototype of Ambiances was composed of three different areas or “environments”: a text editor where an author composes the poem, a minimalist- programming

As a training dataset we used embeddings from baseline model for every examined sequence and as a label for the users’ models we used knowledge about their state - whether the user

Faktor pendukung pemberdayaan masyarakat oleh BWUM Sumatera Barat yaitu; (a) Adanya dukungan dan kepercayaan dari masyarakat kepada Muhammadiyah untuk mengelola wakaf lebih