Matlab - Eds1



Matlab

Matlab is all about matrices. Even adding 2+2 is adding two 1x1 matrices!

After starting, Matlab we can type into the Command Window directly as below though generally it is probably better to save commands into a script file and run that (see next page).

After entering an expression or formula , the answer “ans” is given immediately

>> 2+2

ans =

4

Creating a Script File

Scripts are know as m-files eg test.m

Matlab exercises



Variables

Matlab does not require any type declarations or dimension statements!

eg:

>> num_students = 25

creates a (1-by-1 matrix!) variable named num_students and stores the value 25 as its only element.

Variable names consist of a letter, followed by any number of letters, digits, or underscores.

eg abc123 or abc_123

Numbers

Matlab uses conventional decimal notation, with an optional decimal point and leading plus or minus sign, for numbers.

3 -99 0.0001

9.6397238 1.60210e-20 6.02252e23

1i -2j 3e5i (complex numbers)

(All numbers are stored internally using the long format specified by the IEEE floating-point standard.)

Floating-point numbers have a finite precision of roughly 16 significant decimal digits and a finite range of roughly 10−308 to 10+308.

Operators

Expressions use familiar arithmetic operators and precedence rules.

+ Addition

- Subtraction

* Multiplication

/ Division

\ Left Division

^ Power

Built-In Functions

Matlab provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. For a list of the elementary mathematical functions, type

>> help elfun

For a list of more advanced mathematical and matrix functions, type

>> help specfun

>> help elmat

Matrices

Scalars, Vectors Matrices

In general Matlab stores numeric data in matrices.

(Vectors with only one row or one column, scalars are just 1-by-1 matrices.)

2.1.1 Entering data

To enter a matrix explicitly, simply type in the Command Window

>> A = [1 2 3; 4 5 6; 7 8 9] Typing a row: use a comma or a space as below

For a new column use a semicolon.

or

>> A = [1,2,3; 4,5,6; 7,8,9]

Matlab displays the matrix you just entered:

A =

1 2 3

4 5 6

7 8 9

Once a matrix has been entered, it is automatically remembered in the Matlab workspace. It can be simply referred to by typing A.

Matrix Operations

Multiplication The multiplication symbol * denotes matrix multiplication involving inner products between rows and columns:

if A= [1 3] and B= [2 ; 4]

then

>> A*B

ans =

14

Transpose

The matrix transpose can be applied by using transpose eg transpose(A) or (for real) matrices, by using ’.

eg >> B= [2 4]'

B =

2

4 is exactly the same as B= [2 ; 4]

Determinant The determinant of a matrix can be computed by det().

>> A=[1 2;3 4]

A =

1 2

3 4

>> det(A)

ans =

-2

Inverse The inverse can be obtained just by

>> inv(A)

eg if

>> A=[1 2;3 4] then

>> inv(A)

ans =

-2.0000 1.0000

1.5000 -0.5000

of course if we multiply a matrix by its inverse we get the identity matrix:

>> A*inv(A)

ans =

1.0000 0

0.0000 1.0000

Subscripts

The element in the row i and the column j of A is denoted by A(i,j).

A = [1 2 3; 4 5 6; 7 8 9] and then

>> A(1,3) + A(3,2)

will give the result

ans =

11

(If you assign a value to a position that is out of the range of the matrix, Matlab increases the size automatically! eg)

>> X = A; (where A = [1 2 3; 4 5 6; 7 8 9])

>> X(3,4) = 10

X =

1 2 3 0

4 5 6 0

7 8 9 10

Colon operator

The expression

>> 1:10 is a row vector containing the integers from 1 to 10: So just type 1:10 in the command window.

ans =

1 2 3 4 5 6 7 8 9 10

or ans =

Columns 1 through 8

1 2 3 4 5 6 7 8

Columns 9 through 10

9 10

To specify an increment: Type:

>> 8:2:20

ans =

8 10 12 14 16 18 20 (Goes up by 2 starting at 8)

We can specify non-unit spacing or negative spacing:

>> 15:-2.5:5

ans =

15 12.5 10 7.5 5

Subscript expressions involving colons refer to portions of a matrix:

eg Make this matrix:

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

A =

1 2 3

4 5 6

7 8 9

A(:,1) refers to all the elements in the 1st column (ie the whole first column)

>> A(:,1)

ans =

1

4

7

A(1,:) refers to all the elements in the 1st row (ie the whole first row)

>> A(1,:)

ans =

1 2 3

>> A(1:2,1) reads as the elements from 1:2 (ie row 1->row2) of the 1st column.

ans =

1

4

>> A(1:2,1) reads as the elements from 1:2 of the 1st row.

>> A(1,1:2)

ans =

1 2

The keyword end refers to the last row or column. eg

>> A(:,end) gives all the elements from the last column:

ans =

3

6

9

>> A(end,:) gives all the elements from the last row

:

ans =

7 8 9

A(:) serializes the whole matrix.

Make this matrix:

A= [1 2 ; 3 4]

A =

1 2

3 4

There are two different ways we can “square a matrix”: Either multiply by itself or individually square each element respectively.

1.

A^2

ans =

7 10

15 22

“Dot Wise” Operations

2.

A.^2

ans =

1 4

9 16

To independently multiply the corresponding elements:

A.*B

so if we have

A= [1 2 ; 3 4]

B= [1 3 ; 2 1] then

A.*B

ans =

1 6

6 4

Solving Equations

eg A =

0 1

-2 -3

and B= [2 ;-8]

for AX=B

>> inv(A) * B

ans =

1

2

But easier and quicker is:

>> x= A\B

x =

1

2

We have just solved =ns of the form Ax=B for X Solution -> x= A\B.

What if we wished to solve an equation of the form xA=B? Solution -> x= A/B.

eg

>> x= [1;2]

x =

1

2

>> A = [3 4]

A = 3 4

>> B = x * A

B =

3 4

6 8

>> x = B/A

x =

1

2

Matlab provides different functions that generate basic matrices.

zeros All zeros (learn : important!)

ones All ones (learn : important!)

rand Uniformly distributed random elements

randn Normally distributed random elements

Here are some examples:

>> Z = zeros(2,4) ie 2 rows of 4 columns of 0’s

Z =

0 0 0 0

0 0 0 0 zeros(5,5) can be written as shorthand as zero(5) - beware!

>> F = 5 * ones(3,3)

F =

5 5 5

5 5 5

5 5 5

>> R = randn(4,4) A 4x4 matrix of uniform random variables.

R =

0.6353 0.0860 -0.3210 -1.2316

-0.6014 -2.0046 1.2366 1.0556

0.5512 -0.4931 -0.6313 -0.1132

-1.0998 0.4620 -2.3252 0.3792

>> N = 10 * rand(1,10) Multiply each by 10.

0.3571 8.4913 9.3399 6.7874 7.5774 7.4313 3.9223 6.5548 1.7119 7.0605

>> N = fix(10*rand(1,10))

fix means Round towards zero. (Type help fix)

N =

9 2 6 4 8 7 4 0 8 4

Adding a value to a matrix: Adds it to every element eg

>> A= [1 2; 3 4 ]

A =

1 2

3 4

>> A+1

ans =

2 3

4 5

Concatenation

is the process of joining small matrices to make bigger ones. The pair of square brackets [] is the concatenation operator. For example if:

>> v = [1;4;7] v is a (column) vector in this case.

>> A = [v v+1 v+2] (v+1 means add 1 to every element in v,)

v =

1

4

7

A =

1 2 3

4 5 6

7 8 9

Deleting Rows And Columns

Complete rows and columns can be deleted by using just a pair of square brackets

>> X = A;

>> X(:,2) = [] ie column 2 is deleted. Don’t forget that : means “whole” (row or column).

This changes X to

X =

1 3

4 6

7 9

Controlling Input and Output

Format Function

The format function controls the numeric format of the values displayed by Matlab. The function affects only how numbers are displayed, not how Matlab computes or saves them.

Examples: If x = [4/3 1.2345e-6] then

>> format short

x =

1.3333 0.0000

>> format short e

x =

1.3333e+000 1.2345e-006

>> format short g

x =

1.3333 1.2345e-006

>> format long

x =

1.33333333333333 0.00000123450000

>> format rat

x =

4/3 1/810045

In addition

>> format compact

Suppresses many of the blank lines that appear in the output. (Very useful)

Entering Long Statements

If a statement does not fit on one line, use an ellipsis (three periods) ... followed by Return or Enter to indicate that the statement continues on the next line. For example,

>> s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 ...

1/8 + 1/9 - 1/10 + 1/11 - 1/12;

Blank spaces around the =, +, and - signs are optional, but they improve readability.

Programming

Flow Control

if

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.

try this code:

A=1

B=2:

if A > B

’greater’

elseif A < B

’less’

elseif A == B

’equal’

else

’Unexpected situation’

end

ans =

less

switch and case

The switch statement executes groups of statements based on the value of a variable or expression. It’s like a multiple If statement.

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.

switch(value)

case 0

'Its zero'

case 1

'Its one'

rwise

'Not Sure'

end

ans =

Its one

Unlike the C language switch statement, 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.

for

The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements.

for i = 1:12 ‘means 1,2, …12.

A(i) = 5;

end

Result: 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0

for i = 3 : 3 : 12

A(i) = 5;

end

The result will be a 1-by-12 vector with every third value equals 5.

A =

0 0 5.00 0 0 5.00 0 0 5.00

while

The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.

x=0;

while x < 4

x=x+1

end

x =

1.00

x =

2.00

x =

3.00

x =

4.00

while A > B

A = A - 1;

end

continue

The continue statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it.

break

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

Scripts and Functions

There are two kinds of m-files:

Scripts (as we have seen)

When you invoke a script, Matlab simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate.

This example script that generates 32 random values with randn and displays the values as bar graphic.

r = zeros(1,32);

for n = 1:32

r(n) = randn;

end

r

bar(r)

Result: r = Columns 1 through 11

0.5377 1.8339 -2.2588 etc

If we saved this in a file called barrandn.m, the script can be started by simply typing barrandn in the command line.

Functions

Functions are M-files that can be called from the “main” part of the program. They can accept input arguments and return output arguments.

The name of the m-file and of the function should be the same!!

Functions operate on variables within their own workspace, separate from the workspace you access at the Matlab command prompt.ie they are local to that workspace.

Example function sumup with one parameter a that sums up the values from 1 to a.

File sumup.m:

function r = sumup(a)

% Function that sums up the values from 1 to a

sum = 0;

for i = 1:a

sum = sum + i;

end

r = sum;

Typing >> sumup(5) at the command window (or from your test.m file) produces:

ans = 15 > fhandle = @sumup;

>> fhandle(5) can then be used to run the function sumup; to give the same result as before ie ans = 15

Evaluate a function handle using the Matlab feval function. The function plot_fhandle, shown below, receives a function handle fhandle and data data, and then performs an evaluation of the function handle on that data using feval.

function x = plot_fhandle(fhandle,data)

r = data;

for i = 1:prod(size(data)) %use numel instead

r(i) = feval(fhandle,data(i));

end

x = r

plot(data,r,’+’)

Typing these 2 commands in the Matlab command line

v = [ 1 2 3 4 5 ];

plot_fhandle(@sumup,v)

computes the results of the function sumup for the values within v and plots them.

summary: This is simply a function calling another function:.

clc;

v = [ 1 2 3 4 5 ];

plot_fhandle(@sumup,v)

function x = plot_fhandle(fhandle,data)

r = data; %Just to make it the same size? ie dim it

for i = 1:mumel(data)

r(i) = feval(fhandle,data(i));

end

x=r;

plot(data,r,'+');

function r = sumup(a)

% Function that sums up the values from 1 to a

sum = 0;

for i = 1:a

sum = sum + i;

end

r = sum;

y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;

Plotting

Matlab provides a variety of functions for displaying vector data as line plots,

as well as functions for annotating and printing these graphs.

Create Line Plots

If y is a vector, plot(y) produces a linear graph of the elements of y

versus the index of the elements of y.

If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.

Adding Plots to an Existing Graph

You can add plots to an existing graph using the hold command. When you set hold to on,

Matlab does not remove the existing graph; it adds the new data to the current graph, rescaling if the new data falls outside the range of the previous axis limits.

The command hold

plots both graphs in one figure. The hold command can be turned off by typing hold off.

clc;

X= [1:10];

Y = 2* X;

plot(X,Y)

hold on;

Y = X.^2;

plot(X,Y)

The command: >> grid on; shows an underlying grid within the figure.

Specifying Data Point Markers, Line Styles And Colors

You can define the colors and line styles.

It is also possible to plot only markers at the data points.

plot(X,Y ,'r+')

plots a red ’+’ at each data point.

plot(X,Y ,'r')

plots a red curve

>> plot(I(100,1:20:end),’-rs’,’LineWidth’,2,...

’MarkerEdgeColor’,’k’,...

’MarkerFaceColor’,’g’,...

’MarkerSize’,10);}

Plots a graph (Figure 2) of every 20th pixel of row 100 and marks each data

point with a green rectangle.

Figure 2: Plot of every 20th pixel of row 100 in Image I

Setting Axis Parameters

Matlab selects axis limits based on the range of the plotted data.

You can specify the limits manually using the axis command.

Call axis with the new limits defined as a four-element vector.

axis([xmin,xmax,ymin,ymax])

By default, Matlab displays graphs in rectangular axes that have the same aspect ratio as the figure window. Matlab provides control over the aspect ratio with the axis command.

The command axis square makes the x- and y-axes equal in length.

The square axes has one data unit in x to equal two data units in y.

If you want the x- and y-data units to be equal, use the command axis equal.

This produces axes that are rectangular in shape, but have equal scaling along

each axis.

If you want the axes shape to conform to the plotted data, use the tight option in conjunction with equal. axis equal tight

4.2.5 3D Plots

The plot3 function displays a three-dimensional plot (Figure 3) of a set of data

points. Example

>> t = 0:pi/50:10*pi;

>> plot3(sin(t),cos(t),t)

>> grid on

>> axis square

Symbolic Math

Similar notation, with "D" denoting differentiation, is used for

% for ordinary differential equations by the "dsolve" function.

>> y = dsolve('Dy = -a*y')

y =

C1*exp(-a*t)

% Specify an initial condition for the above de..

>> y = dsolve('Dy = -a*y','y(0) = 1' )

y =

exp(-a*t)

% To produce symbolic output

Method 1 : Use syms: % You can either find the zeros of a symbolic expression, without quotes:

syms a b c x r

r = (a*x^2 + b*x + c) -> r = a*x^2 + b*x + c

solve(r) -> r =

1/2/a*(-b+(b^2-4*a*c)^(1/2))

1/2/a*(-b-(b^2-4*a*c)^(1/2))

% Method 2: Use quotes:

r = solve( 'a*x^2 + b*x + c = 0' ) or solve( 'a*x^2 + b*x + c ' )

% Both of these produce the same result:

r =

1/2/a*(-b+(b^2-4*a*c)^(1/2))

1/2/a*(-b-(b^2-4*a*c)^(1/2))

% The solution could be returned in a structure: eg

S = solve('x^2 + x*y + y = 3', 'x^2 - 4*x + 3 = 0')

Output ->

S =

x: [2x1 sym]

y: [2x1 sym]

So we could further type: S.x

Output ->

ans =

1

3

and S.y

->

ans =

1

-3/2

% The second derivative is denoted by "D2'.

y = dsolve('D2y = -a^2*y', 'y(0) = 1, Dy(pi/a) = 0')

Output ->

y = cos(a*t)

or !

y =

exp(-a*t*i)/2 + exp(a*t*i)/2

It is sometimes desirable to use the simple or simplify function to transform expressions into more convenient forms.

f = cos(x)^2 + sin(x)^2

f = simple(f)

f = 1

Cell Array (Not used much)

>> c= {1,'ed'} % Different types.

c =

[1] 'ed'

>> c{1}

ans =

1

>> c(1)

ans =

[1]

>> c(2)

ans =

'ed'

>> x.i = 1

x =

i: 1

>> x.j = 2

x =

i: 1

j: 2

>> x

x =

i: 1

j: 2

>>

a =

0 3 0 0

0 0 4 0

0 0 0 0

0 0 0 0

>> A=sparse(a)

A =

(1,2) 3

(2,3) 4

>>

>> X=full(A)

X =

0 3 0 0

0 0 4 0

0 0 0 0

0 0 0 0

>>

functions (again)

>> f=@twoX ie f is now just a proxy. (Not used much)

>> f(2)

twoX = 4

Anonymous Functions

>> f=@(x)2*x

>> f(3)

ans = 6

also feval(f,3)

ans = 6

f=@(x)(x^2+3*x)

or f=@(x)x^2+3*x % no difference

>> f(3)

ans = 18

clc;

% A= [1 2];

% B =[3 4];

% Y = arrayfun(@(X)numel(X),A);

% First make a structure s containg 3 arrays f1 (of different sizes).

s(1).f1 = rand(3, 6);

s(2).f1 = magic(12);

s(3).f1 = ones(5, 10);

f = @(x) numel(x.f1) % f is a function handle to our anonymous function.

counts = arrayfun(f, s) % s is passed clumsily as an argument to arrayfun

% arrayfun operates on the three f1 arrays.

% arrayfun calls the function f three times - once on each array in s.

% ie it applies numel to each array in s.

Using C:

Code for book

(ie the booklet? Or printed notes?)

>> mex –setup

Please choose your compiler for building external interface (MEX) files:

Would you like mex to locate installed compilers [y]/n? y

Select a compiler:

[1] Digital Visual Fortran version 6.0 in C:\Program Files\Microsoft Visual Studio

[2] Lcc C version 2.4 in C:\Matlab7\sys\lcc

[3] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio

[0] None

Compiler: 2

Please verify your choices:

Compiler: Lcc C 2.4

Location: C:\Matlab7\sys\lcc

Are these correct?([y]/n): y

Try to update options file: C:\Documents and Settings\O(wner\Application Data\MathWorks\Matlab\R14\mexopts.bat

From template: C:\Matlab7\BIN\WIN32\mexopts\lccopts.bat

Done . . .

>> mex hello.c

>> hello

hello world

>> load handel

>> sound(y,Fs)

>>syms cont’d. Say we defined these two functions:

syms x;

>> f = sym('f(x)')

f =

f(x)

>> g=sym('g(x)')

g =

g(x)

>> pretty(diff(f*g))

/d \ /d \

|-- f(x)| g(x) + f(x) |-- g(x)|

\dx / \dx /

>> pretty(diff(f/g))

d /d \

-- f(x) f(x) |-- g(x)|

dx \dx /

------- - --------------

g(x) 2

g(x)

>> pretty(simple(diff(f^n)))

(n - 1) /d \

f(x) n |-- f(x)|

\dx /

>> syms x a b

>> f=x/(a*x+b)

>> pretty(f)

x

-------

a x + b

>> g=int(f) % integrate f.

g = 1/a*x-b/a^2*log(a*x+b)

>> pretty(g)

b log(a x + b)

x/a - --------------

2

a

>> latex(g)

ans = {\frac {x}{a}}-{\frac {b\ln \left( ax+b \right) }{{a}^{2}}}

>> ccode(g)

ans = t0 = 1/a*x-b/(a*a)*log(a*x+b);

>> fortran(g)

ans = t0 = 1/a*x-b/a**2*log(a*x+b)

>> int(g) % integrate g.

ans = 1/2/a*x^2-b/a^2*log(a*x+b)*x-b^2/a^3*log(a*x+b)+b/a^2*x+b^2/a^3

>> pretty(ans)

2 2 2

x b log(a x + b) x b log(a x + b) b x b

1/2 ---- - ---------------- - --------------- + --- + ----

a 2 3 2 3

a a a a

Partial Differentation:

>> syms x y

>> g= x*y + x^2;

>> diff(g) (Assumes wrt x)

ans =y+2*x

>> diff(g,x) (Same result but explicitly wrt x)

ans =y+2*x

>> diff(g,y) (x*y + x^2 wrt y)

ans =x

page 129

>> syms x x1 x2 theta

>> F=x*(x1*x2 + x1 - 2);

>> findsym(F,1)

ans =x

>> diff(F,x)

ans =x1*x2+x1-2

>> diff(F,x1)

ans =x*(x2+1)

>> diff(F,x2)

ans =x*x1

>> G=cos(theta*x)

G =cos(theta*x)

>> diff(G,theta)

ans =-sin(theta*x)*x

>> syms h n x

>> limit((1+x/n)^n, n, inf)

ans =

exp(x)

>> limit(sin(x)/x,x,0)

ans =

1

>> taylor(cos(x))

ans =

1-1/2*x^2+1/24*x^4

>> taylor(cos(x),8)

ans =

1-1/2*x^2+1/24*x^4-1/720*x^6

>> pretty(vpa('pi',100))

3.14159265358979323846264338327950288419716939937510582097494459230781640\

6286208998628034825342117068

subs

>> syms x s t

>> subs(sin(x),x,pi/3)

ans =

0.8660

>> subs(sin(x),x,sym(pi)/3)

ans =

1/2*3^(1/2)

>> double(ans)

ans = 0.8660

>> subs(g*t^2/2, t, sqrt(2*s))

ans =(x*y+x^2)*s

>> subs(sqrt(1-x^2), x, cos(x))

ans =(1-cos(x)^2)^(1/2)

>> subs(sqrt(1-x^2), 1-x^2, cos(x))

ans =cos(x)^(1/2)

>> syms x

S = x^y

>> subs (S,x,3)

ans =3^y

>> subs(S,{x y},{3 2})

ans = 9

>> subs(S,{x y}, {3 x+1})

ans =3^(x+1)

>> syms a b x y z

expand((a + b)^5)

ans =a^5+5*a^4*b+10*a^3*b^2+10*a^2*b^3+5*a*b^4+b^5

factor(ans)

ans =(a+b)^5

collect(x * (x * (x + 3) + 5) + 1)

ans =1+x^3+3*x^2+5*x

horner(ans)

x*(x*(x+3)+5)+1

>> factor(sym('4248')) % into prime numbers.

ans = (2)^3*(3)^2*(59)

Plotting continuous functions

syms t x y

ezplot(sin(2*x))

>> ezplot(x*exp(-x), [-1 4])

parametric:

Page 138

x = t-sin(t)

y = 1-cos(t)

ezplot(x,y, [-4*pi 4*pi])

>> ezpolar(sin(3*t))

%16.7 Three-dimensional surface graphs

%16.8 Three-dimensional parametric curves

>> x = 3*t / (1+t^3);

y = 3*t^2 / (1+t^3);

z = sin(t);

ezplot3(x,y,z)

>> ezplot3(x,y,z,'animate')

Animation

% curve.m

% Shows animation of a parametric curve being plotted.

hold on

for T=0:.1:4*pi

t=[T T+.1];

plot(2*t.*cos(t)./(t+1),2*t.*sin(t)./(t+1))

axis equal

axis([-2 2 -2 2])

axis off

pause(.01)

end

%16.9 Symbolic matrix operations

a = magic(3)

A = sym(a)

a =

8 1 6

3 5 7

4 9 2

A =

[ 8, 1, 6]

[ 3, 5, 7]

[ 4, 9, 2]

>> syms a b s

K = [a + b, a - b ; b - a, a + b]

-> K =

[ a+b, a-b]

[ b-a, a+b]

>> G = [cos(s), sin(s); -sin(s), cos(s)]

-> G =

[ cos(s), sin(s)]

[ -sin(s), cos(s)]

>> sqr = inline(´x^2´)

>> sqr(3)

>> figure(4)

>> hold on Get ready to plot, but don’t quit plotting until you’re told to.

>> ezplot(´sin(x)´, [-pi,pi]) Graph f(x) = sin x over the interval [−π, π].

>> ezplot(´sin(2*x)´, [-pi,pi]) Graph f(x) = sin 2x over the interval [−π, π].

syms t;

>> ezplot3(t^2*sin(10*t), t^2*cos(10*t), t,'animate');

plot plots matrices

x = -2.9:0.2:2.9;

bar(x,exp(-x.*x),'r')

f = @(x)2*x;

fplot(f, [-1 1])

syms x

syms('pi')

n=1

f = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x);

ezplot(f)



The command who returns a list of all variables in the current workspace, while whos returns the same list with more detailed information about each variable.

>> who

Your variables are:

ans x y

>> whos

Name Size Bytes Class

ans 1x1 8 double array

x 1x1 8 double array

y 1x1 8 double array

Vectors

The function dot computes the dot product of two vectors in Rn .

>> v=[7; 23; 15; 2], w=[5; -2; 1; -8]

v =

7

23

15

2

w =

5

-2

1

-8

>> dot(v,w)

ans =

-1

The length of a vector can also be found directly using the norm function.

>> norm(v)

ans =

28.4077

The function cross computes the cross product of two vectors in R3.

>> v=[3; 2; 1], w=[4; 15; 1]

v =

3

2

1

w =

4

15

1

>> x = cross(v,w)

x =

-13

1

37

The * in scalar multiplication is not optional. eg 2 * A

>> 2A

??? 2

|

Missing operator, comma, or semi-colon.

The rref command is used to compute the reduced row echelon form of a matrix.

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

A =

1 2 3 4 5 6

1 2 4 8 16 32

2 4 2 4 2 4

1 2 1 2 1 2

>> rref(A)

ans =

1 2 0 0 -4 -8

0 0 1 0 -1 -6

0 0 0 1 3 8

The rank of a matrix equals the dimension of its column space – no of independent rows

>> A=[1 2 1 4; 2 3 1 3; 3 2 1 2; 4 3 1 1]

A =

1 2 1 4

2 3 1 3

3 2 1 2

4 3 1 1

>> rank(A)

ans =

3

If we just wanted to find the eigenvectors from scratch, we would use the null command.

>> A=[3 1 1; 1 3 1; 1 1 3]

A =

3 1 1

1 3 1

1 1 3

>> C1 = null(A-2*eye(3),'r') (2 is one Eigen values)

C1 =

-1 -1

1 0

0 1

>> C2 = null(A-5*eye(3),'r')

C2 =

1

1

1

Linear Equations

Systems of equations can also be handled by solve.

>> S = solve('x+y+z=1','x+2*y-z=3')

S =

x: [1x1 sym]

y: [1x1 sym]

The variable S contains the solution, which consists of x and y in terms of z.

>> S.x

ans =

-3*z-1

>> S.y

ans =

2*z+2

Fourier

syms x

syms('pi')

n=1

f1 = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)

ezplot(f1, [-4 4])

Repeat for n=2. (Modify the Fourier file above and run it again.)

Now plot both curves together:

syms x

syms('pi')

hold on

n=2

f2 = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)

ezplot(f2, [-4 4])

n=1

f1 = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)

ezplot(f1, [-4 4])

Now plot the SUM as well – by adding this code to the file above.

f = f1 + f2

h=ezplot(f, [-4 4])

set(h, 'Color', 'm');

Exactly the same effect can be achieved as above using a loop:

syms x

syms('pi')

hold on

f=0

for n = 1:2

c = 8/((2*n-1) * pi)*(-1)^(n+1)*cos((2*n-1)*x)

ezplot(c, [-4 4])

f = f + c

end

h = ezplot(f, [-4 4]);

set(h, 'Color', 'm');

But..

Increase n say 10, 20 etc

You may wish to increase the time interval to demonstrate this periodicity:

h = ezplot(f, [-10 10]);

See page 186 Old Edition Stroud Advanced for the Fourier series formulas

..and page 188 for the method of evaluating the coefficients an for the example above.

x=[0,.1,.5,.4,1.2];

dftx=fft(x)

Output:

dftx =

Columns 1 through 4 :

2.2000 -0.3264 + 0.9874i -0.7736 + 0.7417i -0.7736 - 0.7417i

Column 5 :

-0.3264 - 0.9874i

clc;

x = [0 .1 .5 .4 1.2]

y=0;

for J = 1:5

y=y+exp(-2*pi/5*(J-1)*i)* x(J)

end

syms w a

f = exp(-w^2/(4*a^2));

F = ifourier(f)

F = simple(F)

syms t

f = sin(t)+sin(2*t);

F = fourier(f)

Output:

F = i*pi*(-dirac(w-1)+dirac(w+2)-dirac(w-2)+dirac(w+1))

****************************************************

f= ifourier(F)

Output:

f =

sin(x)*(2*cos(x)+1)

page 14 of notes

syms t a real

a=2;

f = exp (-a * abs(t) );

F = fourier(f)

Output:

F = 4/(4+w^2)

syms a real;

f = exp(-w^2/(4*a^2));

F = ifourier(f);

F = simple(F)

Output:

F = ifourier(exp(-1/4*w^2/a^2),w,x)

Plotting 3D Mesh

x = 0:.5:1;

[X,Y] = meshgrid(x,x);

Z = X.* Y

mesh(x,x,Z);

axis([0 1 0 1 0 2])

xlabel('X');

ylabel('Y');

zlabel('Z');

|X |0 |0.5 |1 |

| |0 |0.5 |1 |

| |0 |0.5 |1 |

| | | | |

|Y |0 |0 |0 |

| |0.5 |0.5 |0.5 |

| |1 |1 |1 |

| | | | |

|Z |0 |0 |0 |

| |0 |0.25 |0.5 |

| |0 |0.5 |1 |

x = 0:.01:1;

[X,Y] = meshgrid(x,x);

Z=0;

for n = 1:2:1

K = -4/(pi*n*sinh(n*pi)); %coefficients

Z = Z + K * sinh(n * pi*(X-1)).* sin(n* pi*Y) ;

end

mesh(x,x,Z);

xlabel('X');

ylabel('Y');

zlabel('Z');

Wave equation

x = 0:.01:1;

[X,T] = meshgrid(x,x);

N = 101;

c=1;

Z=0;

for n = 1:2:N

a = 4/(pi^2)*sin(n*pi/2)/(n^2); %coefficients

Z = Z + a * sin(n * pi*(X)).* cos(n*pi*c*T) ;

end

mesh(x,x,Z);

xlabel('X');

ylabel('Y');

zlabel('Z');

Use n = 1 inc velocity c= 4

Plotting

>> x = -1:.1: 1;

>> y = x.^3

>> plot(y)

Variance Using a Matlab Function

.

No endfunction ??

To run it:

>> polar(t,1-sin(t))

Note the difference using syms or not:

Simulink

See Matlab Help:Building a Model

Drag arrows as shown and then …

Eigen Values/Vectors

Eigen Values/Vectors are used to solve special simultaneous equations.

Type this (in a script file):

A = [ 0 1

-2 -3];

Then try this:

[V,D] = eig(A)

Result

V =

0.7071 -0.4472

-0.7071 0.8944

D =

-1 0

0 -2

So we have:

V =

[1 -1 ;

-1 -2];

and

D =

-1 0

0 -2

Diagonalization

A diagonal matrix is one with numbers only along the leading diagonal the rest being zeros

like so

[ -1 0]

[ 0 -2]

let V be the matrix of corresponding eigen vectors.

If we premultiply a matrix by V and post multiply by inv(V) then the result is a diagonal matrix of the eigen vectors.

eg

page 47 o/heads

clc;

clear all;

format

A = [ 0 1;

-2 -3]

[V D] = eig(A)

V * A * inv(V);

A =

0 1

-2 -3

V =

0.7071 -0.4472

-0.7071 0.8944

D =

-1 0

0 -2

Diagonalization

A diagonal matrix is one with numbers only along the leading diagonal the rest being zeros

like so [ 2 0]

[ 0 3]

BUT rather confusingly diagonalization does not mean finding such a single matrix

It means:

V * A * V-1 -> D

where

V consists of the eigen vectors of A.

D will then be a diagonal matrix with the (corresponding) eigen values along its diagonal.

eg

A = [ 0 1

-2 -3];

V =

1 1

-1 -2

D =

-1 0

0 -2

In Matlab->

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

V = [1 -1 ; -1 -2]; ie 1 -1 -1 0 x x

-1 -2 0 -2 x x

V * A * inv(V) = 0 1

-2 -3

Result:

0 1

-2 -3

easier:

A = [ 0 1;

-2 -3]

[V D] = eig(A)

V * A * inv(V)

Diagonalization continued.

For

A =

0 1

-2 -3

We had the eigen vectors:

E1 =

1

-2

E2 =

1

-1

1. Make a matrix whose columns are the eigen vectors

>> V = [E1 E2]

V =

1 1

-1 -2

2. Then

>> A = inv(V) * D * V

D =

-2 0

0 -1

Note also that

A=V * D * inv(V)

syms v d

[v,d] = eig(A)

>> eigen

A =

[ 0, 1]

[ -2, -3]

v =

[ 1, -1]

[ -2, 1]

d =

[ -2, 0]

[ 0, -1]

SVD

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

U =

-0.2298 0.9732

0.9732 0.2298

D =

3.7025 0

0 0.5402

V =

-0.5257 -0.8507

-0.8507 0.5257

>> U * D * V

ans =

-0.00 1.00

-2.00 -3.00

ie A :

0 1

-2 -3

Note that

>> D^2

ans =

1 0

0 4

So To Raise A to the Power of 10

If

D =

-1 0

0 -2

>> D.^10

ans =

1 0

0 1024

So A^10

>>

ans =

-1022 -1023

2046 2047

>>

rand()

Example 1.

R = rand(3,4)

may produce R =

0.2190 0.6793 0.5194 0.0535

0.0470 0.9347 0.8310 0.5297

0.6789 0.3835 0.0346 0.6711

Polynomials

p = [1 -3 2];

r = roots(p)

backwards:

p = poly(r)

The polyval function evaluates a polynomial at a specified value.

To evaluate p at s = 5, use polyval(p,5)

ans =

110

Straight Line Fit Line of best fit.

X= [1 2 3];

Y= [2 3 1];

p = polyfit(X,Y,1);

Y2 = polyval(p,X);

plot(X, Y, 'o', X, Y2)

grid on

The poly function also computes the coefficients of the characteristic polynomial of a matrix.

Apply this to our eigen matrix

A = [ 0 1;-2 -3]

>> p= poly(A)

p = 1 3 2

>> roots(p)

ans =

-2

-1

Multiplication and Division Of Polynomials.

Multiplication and division correspond to the operations convolution and deconvolution.

The functions conv and deconv implement these operations.

Consider the polynomials x^2 +2x+3 and 4x^2 +5x + 6.

We compute their product like so:

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

c = conv(a,b)

c = 4 13 28 27 18 -> 4x^4 +13x^3 + 28x^2 + 27x + 18

Use deconvolution to divide back out of the product. [q,r] = deconv(c,a)

q = 4 5 6 -> 4x^2 +5x + 6

r = 0 0 0 0 0 -> no remainder

Polynomial Curve Fitting

polyfit finds the coefficients of a polynomial that fits a set of data in a least-squares sense.

p = polyfit(x,y,n)

x and y are vectors containing the x and y data to be fitted, and n is the order of the polynomial to return.

For example, consider the x-y test data. x = [1 2 3 4 5]; y = [5.5 43.1 128 290.7 498.4];

A third order polynomial that approximately fits the data is p = polyfit(x,y,3)

p = -0.1917 31.5821 -60.3262 35.3400

x = [1 2 3 4 5]; y = [5.5 43.1 128 290.7 498.4];

p = polyfit(x,y,3)

x1 = 1:.1:5

y1 =p(1)*x1.^3 +p(2)*x1.^2 + p(3)*x1 +p(4)

plot(x,y,'o',x1,y1)

Partial Fraction Expansion

residue finds the partial fraction expansion of the ratio of two polynomials. This is particularly useful for applications that represent systems in transfer function form. For polynomials b and a, if there are no multiple roots, where r is a column vector of residues, p is a column vector of pole locations, and k is a row vector of direct terms. Consider the transfer function

b = [-4 8];

a = [1 6 8];

[r,p,k] = residue(b,a)

r =

-12

8

p =

-4

-2

k =

[]

Given three input arguments (r, p, and k), residue converts back to polynomial form. [b2,a2] = residue(r,p,k)

b2 =

-4 8

a2 =

1 6 8

Cell Arrays already done – not used much.

Search cell arrays in help

A Cell Array can contain different data types. eg.

C = {'one', 'two', 'three'; 1, 2, 3}

gives:

C =

'one' 'two' 'three'

[ 1] [ 2] [ 3]

>>

Access the data elements using indexed braces:

-> ‘one’

and being an array we must use two indices

in this case

Parentheses are used to access sets of cells eg

C(:,1:2) -> 'one' 'two'

[ 1] [ 2]

It seems we can also use parentheses

to access one element?

>> C(1,1) -> ‘one’

>> C(2,1) -> [1]

that’s because we only have single

elements at each position in the

cell array?

cell(2,3,4) will create 4 cell(2,3) cells.

Create an empty array with the cell function, such as

A = cell(3,4); Creates an array of matrices.

A{1,1} = [1 2]

-> A =

[1x2 double] [] [] []

[] [] [] []

[] [] [] []

and…

an array!

M = cell(8,1); An 8 x 1 array ie 8 rows of matrices.

for n = 1:8

M{n} = magic(n);

End

M ->

>> M{1}, M{2}, M{3}

Matrix of strings

From Help:

S = 'Any Characters' creates a character array, or string. The string is actually a vector that contains the numeric codes for the characters (codes 0 to 127 are ASCII).

S = [S1 S2 ...] concatenates character arrays S1, S2, etc. into a new character array, S.

X=['10','2','3']

X=['10', '2' ,'3']

X(1,2) -> 0 !

but a cell array of strings:

X={'10', '2' ,'3'}

X(1,2) -> '2'

asci

double('a')

ans = 97

double('ac')

ans = 97 99

X=['a', 'c' ]

double(X)

ans = 97 99

str2num

X=['1', '2' ]

str2num(X)

ans = 12

str2double

X=['1', '2' ]

str2double(X)

ans = 12

but str2double will also deal with a cell array differently:

X={'1', '2' }

str2double(X)

ans = 1 2

(but str2num(X) wont!)

Structure

A = struct('name',{'ed','jo','al'},'bal',{10,20,10} );

A(1)

ans =

name: 'ed'

bal: 10

A(1).name

ans =

ed

s = struct('name',{'ed','jo','al'})

s =

1x3 struct array with fields:

name

[pic]

[pic]

same for jo, al.

but:

s = struct('name',{{'ed','jo','al'}})

s =

name: {'ed' 'jo' 'al'}

[pic]

We can convert the numeric bit of a cell array to a matrix

C = {'one', 'two', 'three'; 1, 2, 3};

M= C(2,:)

-> M =

[1] [2] [3]

n = cell2mat(M)

-> n =

1 2 3

:

Interpolation

Polynomial Regression

Based on the plot, it is possible that the data can be modelled by a polynomial function The unknown coefficients a0, a1, and a2 can be computed by doing a least squares fit, which minimizes the sum of the squares of the deviations of the data from the model. There are six equations in three unknowns, represented by the 6-by-3 matrix X = [ones(size(t)) t t.^2]

X =

1.0000 0 0

1.0000 0.3000 0.0900

1.0000 0.8000 0.6400

1.0000 1.1000 1.2100

1.0000 1.6000 2.5600

1.0000 2.3000 5.2900

The solution is found with the backslash operator. a = X\y

a =

0.5318

0.9191

- 0.2387

The second-order polynomial model of the data is therefore Now evaluate the model at regularly spaced points and overlay the original data in a plot. T = (0:0.1:2.5)';

Y = [ones(size(T)) T T.^2]*a;

plot(T,Y,'-',t,y,'o'), grid on

Clearly this fit does not perfectly approximate t

DE’s



All of the differential equations have the same syntax that you must use, and the same input and output arguments. All of the solvers require three input arguments: a function handle to the differential equation you want to solve, a time interval over which to integrate, and a set of initial conditions. Let us suppose we want to solve the simple differential equation y' = y, y(0) = 1, which has the true solution y(t) = e^t. Suppose we want the solution between t = 0 and t = 1.

To use function handles, you must first create an M-file with the function in it like so:

function Yprime = func(t, y)

Yprime = 0;

Yprime = y;

… and call it thus: ode45(@func, [0,1], 1) interval is [0,1]and when t= 0 y = 1.

The result: (ie a graph for free)

On the other hand if we use:

[t,y]=ode45(@func, [0,1], 1) we just get the matrices t and y which is the solution.

t =

0

0.0250

0.0500

0.0750

...

0.9750

1.0000

y =

1.0000

1.0253

1.0513



2.6512

2.7183

3-D Plot

x = -1.5:.04:1.5;

y = -1.5:.04:1.5;

[X,Y] = meshgrid(x,y);

Z = X.^2+ Y.^2 + Y -1;

mesh(X,Y,Z)

xlabel('X');

ylabel('Y');

zlabel('Z');

Z=X.^3- X.^2 - Y.^2 + 8 ;

cat

Given

A = [ 1 2 ;

3 4 ]

B = [ 5 6 ;

7 8 ]

concatenating along different dimensions produces

[pic]

down across back

C=cat(3,A,B)

C(1,1,2) -> 5

ie 3nd dimension 1st element

mind you:

>> [A B]

ans =

1 2 5 6

3 4 7 8

>> [A; B]

ans =

1 2

3 4

5 6

7 8

Cell Array revisited

Cell arrays can contain arrays as elements

Cell arrays are indexed to return the “composite” element in this case an array at that position

eg if

C = {[1], [2 3 4];

[5; 9], [6 7 8; 10 11 12]};

C =

1 2 3 4

5 6 7 8

9 10 11 12 The arrays don’t have to “fit”….

then

C{2,1}

produces the array at position (1,1)

ans =

5

9

but we can convert all to numbers:

A = cell2mat(C) …but the arrays must “fit” to use cell2mat.

A =

1 2 3 4

5 6 7 8

9 10 11 12

then obviously eg A(2,1) -> 5.

Cell Array can also be used for variable length strings



clc;

clear all;

A = {'ed' 'marge'}

A{1}

A{1}(1)

A =

'ed' 'marge'

ans =

ed

ans =

e



mvec = [77 65 84 76 65 66];

sprintf('%s ', char(mvec))

A = pi*100*ones(1,5);

sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)



s1 = 'Yes';

s2 = 'No';

tf = strcmp(s1,s2)



S = strtrim(str)

C = strtrim(cstr)

>> version

ans =

8.1.0.604 (R2013a)

available in Matlab R2014b

clc;

clear all;

% datetime('06301994')

% d = [20140628 20140701 20140704]

% t = datetime(d,'ConvertFrom','yyyymmdd')

% % d = yyyymmdd(t)

% DateStrings = {'2014-05-26';'2014-08-03'};

% t = datetime(DateStrings,'InputFormat','yyyy-MM-dd');

% t = datetime('now','TimeZone','local','Format','d-MMM-y HH:mm:ss Z')

Y = [2014;2013;2012];

M = 01;

D = [31;30;31];

t = datetime(Y,M,D)

The meaning of the : (colon) operator. repeated

: means “every element” .

eg

A = [1 2 ;3 4]

A =

1 2

3 4

A( : , 2) %means every element in column 2.

ans =

2

4

A( 2 , : ) %means row 2 every element.

ans =

3 4

Variance revisited

clc;

clear all

format rat

A=[1 2 3]

var(A,1)

ans =

2/3 (divides by n)

var(A,0)

ans =

1 (divides by n-1)

matrix syms

clc;

clear all

syms q

A=[q 1-q 0;

0 q 1-q;

0 0 q ]

A^2

ans =

[ q^2, -2*q*(q - 1), (q - 1)^2]

[ 0, q^2, -2*q*(q - 1)]

[ 0, 0, q^2]

------------------------------

clc;

clear all

q = .6

A=[q 1-q 0;

0 q 1-q;

0 0 q ]

A^2 * [31 0 0]'

ans =

11.1600

0

0

fprintf

For example

fprintf('Call Price at t=0 is %4.5f', V1(1))

The % means it’s is a “placeholder” for the value that’s after the comma.

f means print a decimal.

4.5'means print 4 numbers max to the left of the dec place (I think!) and 5 dec places to the right.

ie 3.74779

% ….. s means string etc.

clear all;

format compact

syms k1 k2 k3 s ;

n=3;

I = eye(n);

k1=1;

A0= [-3 1 0 ;

0 -2 1

-2*k1 -2*k2 -2*k3-4]

D=s*I -A0

dt = det(D)

C=collect(dt,s)

coeffs(C,s)

A0 =

[ -3, 1, 0]

[ 0, -2, 1]

[ -2, -2*k2, - 2*k3 - 4]

D =

[ s + 3, -1, 0]

[ 0, s + 2, -1]

[ 2, 2*k2, 2*k3 + s + 4]

dt =

6*k2 + 12*k3 + 26*s + 2*k2*s + 10*k3*s + 2*k3*s^2 + 9*s^2 + s^3 + 26

C =

s^3 + (2*k3 + 9)*s^2 + (2*k2 + 10*k3 + 26)*s + 6*k2 + 12*k3 + 26

ans =

[ 6*k2 + 12*k3 + 26, 2*k2 + 10*k3 + 26, 2*k3 + 9, 1]

>>

Matrix tricks

swap 2 columns

clc;

A = magic(4)

A(:,[1 3]) = A(:,[3 1])

ingenious!

Logical

A= [107,108,109,110,111];

A([0 1 0 1 0]) doesn’t work but

A(logical([0 1 0 1 0])) does

ans =

108 110

A([false true false true false]) does as well!

ismember

A= [107,108,109,110,111];

H1 = [108 110]

X=ismember(A,H1)

A(X)

← same result

ans =

108 110

setdiff

A= [107,108,109,110,111];

H1 = [108 110]

setdiff(A,H1)

A =

107 109 111 ie “A-B”

setdiff rows

A = [1,10 ;2, 20;3,30]

B = [1,10 ;2, 20]

A = setdiff(A,B,'rows')

A =

1 10

2 20

3 30

B =

1 10

2 20

A = use C?

3 30

For cell arrays:

C = {'one', 'two', 'three'; 1, 2, 3}

A = {'one', 'three'; 1, 3}

D = setdiff(A,C,'rows')

Warning: The 'rows' input is not supported for cell array

inputs.

intersect

A= [107,108,109,110,111];

H1 = [108 110];

intersect(A,H1)

ans =

108 110

A = [1,10 ;2, 20;3,30]

B = [1,10 ;2, 20]

intersect(A,B,'rows')

|A = |B = |ans = |

|1 10 |1 10 |1 10 |

|2 20 |2 20 |2 20 |

|3 30 | | |

using cell arrays:

C = {'one', 'two', 'three'; 1, 2, 3}

A = {'one', 'three'; 1, 3}

X= intersect(C,A,'rows')

wont work!

neither will:

C = {10, 20, 30; 1, 2, 3}

A = {10, 30; 1, 3}

X= intersect(C,A,'rows')

Warning: The 'rows' input is not supported for cell array inputs.

cell2table

cell2table not available in R2013a

cell2mat cell2mat is OK

C = {10, 20, 30; 1, 2, 3}

T = cell2mat(C)

C =

[10] [20] [30]

[ 1] [ 2] [ 3]

T =

10 20 30

1 2 3

C must be numbers?

clc

clear;

A=[1 2; 2 4 ];

B=[3; 4; 5];

D=[3; 4 ;5];

C={A B D};

f = @(x) numel(x)

num = arrayfun(f, C)

->num =

1 1 1 why?

Matlab & Excel

From Excel File Options, Go, AddIns Browse

C:\Program Files\MATLAB\R2013a\toolbox\exlink

[pic]

or Browse to:

ok

Close Matlab. From Excel Matlab tab on the Ribbon choose Preferences

C:\Program Files\MATLAB\R2013a

Maybe need to do the above and start Excel which starts Matlab

Highlight the data in Excel

From The Ribbon:

o

Matlab will be open on the task bar at the bottom.

From Matlab: Data will appear as a WorkSpace variable

Work with MATLAB Functions in Microsoft Excel



htp://uk.help/exlink/index.html

There are two ways that we can send and get data from Matlab.

Method1: Worksheet Functions:

From the spreadsheet simply type in one of the following worksheet functions.

Putting data into Matlab:

MLPutMatrix

eg = MLPutMatrix(“M”,A1:A2)

Matlab:

[pic]

Getting data from Matlab:

MLGetMatrix

We will return our matrix M from Matlab:

eg = MLGetMatrix(“M”,A1:A2)

[pic]

MLEvalString

=MLEvalString("b=2")

Method2: Using Excel VBA

test.xlsm Matlab sheet. Matlab Button

Moving Data from Excel -> Matlab

PutMatrix Excel -> Matlab

Private Sub cmdMatlab_Click()

MLPutMatrix "M", Range("A1:A2")

End Sub

very dynamic!

MLPutVar using a variable: Excel -> Matlab

Dim myVar As Variant

myVar = Array(2, 5)

MLPutVar "T", myVar

Not sure why T is a 2 x 1.

Array must produce a column vector not a row vector.)

Moving Data from Matlab -> from Excel VBA

GetMatrix from Matlab ->Excel

Write this in Excel:

Private Sub cmdMatlab_Click()

MLGetMatrix "M", "B1:B2"

MatlabRequest

End Sub

MLGetVar using a variable: from Matlab ->Excel

Write this in Excel:

Matlab Excel VBA

MLPutMatrix "M", Range("A1:A2")

Dim myVar As Variant

MLGetVar "M", myVar

MsgBox myVar(1, 1)

I don’t see how myVar can be anything but a Variant.

Running a Matlab .m file from Excel.

Make this .m file called eds.m in C:\Program Files\MATLAB\

clc;

Cols={1,3;4,5;1,2;3,4;5,4}

B = sortrows(Cols,2) %sorts the matrix Cols by column 2.

Top = B(1:3,:)

Run this from Excel:

Note that we will see nothing in the Matlab Command Window.

We can only tell if it has run OK by looking at the WorkSpace variables created:

We could also run our Matlab .m file from the Matlab command another .m file like so

MLEvalString ("eds”)

MAk sure that eds.m is in the current folder

Reading Data from an Excel Spreadsheet.

xlsread Reads an Excel spreadsheet file

Syntax num = xlsread(filename)



[num,txt,raw] =

xlsread('E:\Users\Ed\Desktop\Daniel\SPE350CES_LVver1.xlsm','Data','A5:E9

')

This command produces THREE! almost identical arrays: num, txt, raw

num just reads numbers so will miss the first few columns!:

Likewise txt will miss the numbers!

So we need raw: which will read everything!

[x,y,z]is just as good as [num,txt,raw] but it appears none can be omitted!

So to write it back: use xlswrite.

clc;

clear;

[x,y,raw] = xlsread('E:\Users\Ed\Desktop\Daniel\SPE350CES_LVver1.xlsm','Data','A5:E9')

Cols=raw(:,[1,5])

B = sortrows(Cols,2)

Top= B(1:3,:)

xlswrite('E:\Users\Ed\Desktop\Daniel\SPE350CES_LVver1.xlsm',Top,'Data','O5:P7')

(It’s OK if the spreadsheet is open.)



Spreadsheet Link EX Functions

Top of Form

Bottom of Form

Startup and Shutdown

|matlabinit |Initialize Spreadsheet Link EX and start MATLAB |

|MLAutoStart |Automatically start MATLAB |

|MLClose |Stop MATLAB |

|MLOpen |Start MATLAB |

Customization

|MLMissingDataAsNaN | Set empty cells to NaN or 0 |

|MLShowMatlabErrors |Return standard Spreadsheet Link EX errors or full MATLAB errors using MLEvalString |

|MLStartDir |Specify MATLAB current working folder after startup |

|MLUseCellArray |Toggle MLPutMatrix to use MATLAB cell arrays |

|MLUseFullDesktop |Specify whether to use full MATLAB desktop or Command Window |

Data Export to MATLAB

|MLAppendMatrix | Create or append MATLAB matrix with data from Microsoft Excel worksheet |

|MLDeleteMatrix | Delete MATLAB matrix |

|MLPutMatrix | Create or overwrite MATLAB matrix with data from Microsoft Excel worksheet |

|MLPutRanges | Send data in Microsoft Excel named ranges to MATLAB |

|MLPutVar |Create or overwrite MATLAB matrix with data from Microsoft Excel VBA variable |

Data Import from MATLAB

|MLGetFigure | Import current MATLAB figure into Microsoft Excel spreadsheet |

|MLGetMatrix | Write contents of MATLAB matrix to Microsoft Excel worksheet |

|MLGetVar | Write contents of MATLAB matrix in Microsoft Excel VBA variable |

MATLAB Commands in Microsoft Excel

|matlabfcn | Evaluate MATLAB command given Microsoft Excel data |

|matlabsub | Evaluate MATLAB command given Microsoft Excel data and designate output location |

|MLEvalString | Evaluate command in MATLAB |

|MLShowMatlabErrors | Return standard Spreadsheet Link EX errors or full MATLAB errors using MLEvalString |

Classes (for instruction leave out methods here)

clc;

clear; % take care to use this!

p0 = Part; % Calls no-argument constructor

p1 = Part(1);% Calls 1-argument constructor % Public (write) access !

p2 = Part(2);% Calls 1-argument constructor % Public (write) access !

p1.i + p2.i % Public (read) access !

p2.mulltTen()

------------------------------------- Part.m ------------------------------------------

classdef Part

properties % Property

i

end

methods

function obj = Part(j) % Constructor

if nargin == 0;

bj.i = 0;

elseif nargin == 1

obj.i = j;

end

end % End this function.

function m = mulltTen(obj)

m = obj.i * 10;

end

end % End methods

end % End Class

Excellent Matlab Help:



Methods - start again!

clc; clear; % take care to use this.

p0 = Part; % Calls no-argument constructor

p1 = Part(1);% Calls 1-argument constructor % Public (write) access !

p2 = Part(2);% Calls 1-argument constructor % Public (write) access !

p1.i + p2.i % Public (read) access !

mulltTen(p1)

sumSq(p1,2)

--------------------------------------------------------------------

classdef Part

properties % Property

i

end

methods

function obj = Part(j) % Constructor

if nargin == 0;

obj.i = 0;

elseif nargin == 1

obj.i = j;

end

end % End this function.

function m = mulltTen(obj)

m = obj.i * 10;

end

function s = sumSq(obj,j) % Method

s = obj.i^2 * j^2;

end

end % End methods

end % End Class

conditional breakpoint

---------------------------------------------

XData * YData

clc

figure

x = -pi:0.1:pi;

y = sin(x);

plot(x,y,’k’);hold on

h = plot(x,y);

axis([-4 4 -1 2])

xdata = get(h,'XData');

ydata = get(h,'YData');

set(h,'YData',ydata+1);

-------------------------------------

y = evrnd(0,3,100,1);

100 norm rand with mean 0 sd 3

-------------------------------------

-----------------------

Typing a command without a semicolon will cause “echo” to the screen.

Once A has been defined we may see its value at any time by simply typing A.

MATLAB is case sensitive.

To clear the Command Window type clc.

Matlab is very case sensitive.

Take care. All Matlab variables persist. So even when you run a new program the old variables still exist. Maybe start with clear all.

(If your command Window is not visible it might have been minimized thus:)

[pic]

To set a default overall layout choose Layout from the menu bar:

[pic]

o Click New.

Take care your file is saved before running – It may run an old version!

Variables may be cleared by going to Clear Workspace on the Home menu.

o Enter code and save it as test.m

o Run the script by typing its filename.

o The result of running the script appears.

Hint: Make your first command in the script file clc to clear the screen each time eg

clc

A=1

o To edit, either double-click on the file or use the Open button above.

The % sign can be used to comment out a line eg

% Unexpected situation

Up-arrow on the keyboard gives the previous command.

e represents exponential 10.

Adding a matrix to its transpose produces a symmetric matrix:

A = [1 2 3; 4 5 6; 7 8 9]

>> A + A’

ans =

2 6 10

6 10 14

10 14 18

to format as rational numbers use

>> format rat

>> inv(A)

ans =

-2 1

3/2 -1/2

Hint: To retrieve a previous command, use the up arrow on the keyboard.

The retrieved line can be edited as well!

(Which of these two output formats you get will depend on how cramped your Command Window is!)

: means “all elements in”

Row 1 all elements.

All elements Column 1.

Same as A(:,3)

Same as A(3,:)

This is equivalent to the matrix multiplication A*A (try it) but…

Remember where the dot goes – after the variable – A in this case.

… the dot now means square each element independently.

Remember where the dot goes – after the first variable. (This is not always easy to remember – so take good note.)

0x + y = 2

-2x – 3y = -8

Not B\A !

Backslash not forward slash.

clc;

A= [3 2;

1 2];

B= [2 2;

1 3];

C=A*B;

% AB = C

Arep = C *inv(B);% ie A or C/B ie C by inverse of B

Brep = inv(A)*C; % ie B or A\C ie inverse of A times C

Arep = C/B

Brep = A\C

Arep =

3 2

1. 2

2.

Brep =

2 2

1 3

A =

1 2 3

4 5 6

7 8 9

Saving and Loading

The save function saves variables that exists in the MATLAB Workspace.

For example if

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

To save this variable in a (binary) file, type

:

>> save matrix. A

[pic]

The load function reads binary files or reads text files containing numeric data.

eg load matrix A;

For example loading a text file containing these four lines. The statement

>> load matrix .mat

reads the file matrix.mat and creates a variable A! containing the example matrix. ??

To restore default formatting use

>> format

>> A = magic(2)

->

A =

1.00 3.00

4.00 2.00

If one true elseif is encountered no toher subsequent elseif will be considered.

switch is not really as useful as it looks. Rather a glorified menu system. Multiple ifs , elseifs etc are more flexible.

clear will clear all variables.

Remark: The Matlab for loop is very slow. Try to avoid it. eg

Instead of the example given above, use:

A(3:3:12) = 5

It sums numbers from 1 to whatever is passed (a).

In Matlab the function name must be the same as the filename !

end is sometimes unnecessary.

function using @

The @ notation allows us to use a function in the same file (Recall that we need to make a separate file for an “ordinary” function.

y = @(t) t.^2 + 2*t; ;

y(2) % -> 4

This calls the first function plot_fhandle.

We are effectively creating a handle to the sumup function (see below) saying

fhandle = @sumup.

feval is necessary to call the second function.

data(i) assumes the values 1,2,3,…

This is a rather clumsy way of passing to the a of the the sumup function.

Solves the de. D means first derivative.

No need for syms!

pause % Strike any key to continue.

pause will wait for keystroke.

>> y = dsolve('Dy = t')

y = 1/2*t^2+C1

Note that t is the default in dependent variable – not x.

But still needs to be a separate file!

But still needs to be a separate file!

Same as before but it is not given a name which was twoX in that case.

Now we don’t need a separate file ( but our function is limited.)

f is a function handle to our function 2*x.

See use eg for fimplicit3.

Either use our function handle or a built-in eg @sin.

#include "mex.h"

void mexFunction

(

int nargout,

mxArray *pargout [ ],

int nargin,

const mxArray *pargin [ ]

)

{

mexPrintf ("hello world\n") ;

}

Write a c function

clc;

syms x;

f = sym('f(x)');

g = sym('g(x)');

pretty(diff(f*g)

f(x) diff(g(x), x) + g(x) diff(f(x), x))

diff(f(x), x) f(x) diff(g(x), x)

------------- - ------------------

g(x) 2

g(x)

limits

Substitution into a syms expression.

clc;

syms x s t

subs(sin(x),x,pi/3)

ans =

3^(1/2)/2

syms x

z1= 2*x

z2=3*x

z=z1+z2

>> z=z1+z2

z =

5*x

ezplot(z)

eye(3) is a 3x3 identity matrix.

Eigen values are 5, 2, 2.

Eigen vectors are

[ 1, -1, -1]

[ 1, 1, 0]

[ 1, 0, 1]

use A= syms(A) and syms a,b.

Save this code as Fourier.m

[pic]

[pic]

You may need to close this ‘figure’ before running the program again lest more graphs are ADDED if you run the since the hold is on.

clc will clear the command window.

You may wish to switch off the blue graphs ie comment out

%ezplot(c, [-4 4])

Fourier’s theorem says that any periodic wave in this case a periodic square wave can be synthesized by a sum of sin or cos functions.

syms t

f = dirac(t);

F = fourier(f)

Output:

F = 1

Note the dot – otherwise it will multiply the 2 matrices together – not piecewise.

Page 20 M2 notes

n = 1

n = 3

n = 101

n = 5

Wave.m

Page 46 lecture o/heads.

MUST save this as a separate file.

MUST be named variance.m

function varn = variance(d1,d2,d3)

m = (d1 + d2 + d3)/3;

varn = ((d1-m)^2 + (d2-m)^2 + (d3-m)^2)/3.0;

% sqrt to get sd

See variance.m

>> s= variance(1,2,3)

Result:

s =

0.6667

>> syms r

>> diff (r^2)

ans =

2*r

If we don’t use syms:

>> clear r

>> diff (r^2)

??? Undefined function or variable 'r'.

>> x=2;

>> x + x

ans =

4

>> syms x

>> x+x

ans =

2*x

o New Model.

Model ...

o Sine Wave.

o Sources.

o Hold down the control key and then drag.

o Double-click to open Scope window.

clc;

A = [ 0 1

-2 -3];

[V,D] = eig(A)

0.7071 and -0.4472

--0.7071 0.8944

are the eigen vectors. Eigen vectors are not unique. It is really just the ratios y:x that we are interested in so for example these below are equivalent to these respective eigen vectors.

1 1

-1 -2

-1 and -2 are the (corresponding) eigen values.

Ex: Show

A*V = V*D

Eigen values and eipective eigen vectors.

1 1

-1 -2

-1 and -2 are the (corresponding) eigen values.

Ex: Show

A*V = V*D

Eigen values and eigen vectors are defined such that AX = λX where X is an eigen vector and λ is a corresponding eigen value.

Show that this is true in both cases for our matrix A.

Here’s the first one done for you:

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

lam1 = -1;

X= [ 1

-1] ;

A*X -> [ -1

-1 ] ;

lam1*X -> [ -1

-1 ] ;

In Matlab P-1 is inv(P).

V is the matrix whose columns are the eigen vectors of A.

.. and D is the result - a diagonal matrix whose diagonal is the eigen values of A.

Note AV=VD

V * D

A * V

ans =

-0.7071 0.8944

0.7071 -1.7889

ans =

-0.7071 0.8944

0.7071 -1.7889

ie same.

A =

0 1

-2 -3

V =

0.7071 -0.4472

-0.7071 0.8944

D =

-1 0

0 -2

Ref: wiki diagonalizable matrix

What if we wanted to find A10?

It so happens that when we multiply these out we get a purely diagonal matrix D whose leading diagonal contains the eigen values of A.

Now A10 => ?

A10 = (P D P-1)10 = P D10 P-1

So A10 = P D10 P-1

Where can D^10 easily be found using D.^10

note V A V-1 -> D

ie the eigen values across the leading diagonal.

A^2 =

0 1 0 1 -2 -3

-2 -3 -2 -3 = 6 7

Must be in this order: inv(V) * D * V

(V doesn’t need to be normalized.)

A diagonal matrix results whose diagonal is the eigen values!

Corresponding to the eigen vectors.

Eigen vectors.

Eigen values are -1 & -2

V is also a matrix of eigen vectors but normalized.

U is the inverse of V and D is the diagonal vector - of eigen values.

A^2 is also just

V * D.^2 * inv(V)

One of these sandwich matrices is the matrix of A’s eigen vectors and the other is the inverse of this.

1 1 1 0 2 1

-1 -2 0 4 -1 -1

-1 4 2 1

-1 8 -1 -1

-2 -3

6 7

o Just square the elements!

eg A^10 is just

P * D.^10 * inv(P)

If D is a diagonal matrix then eg D^10 is easily obtained by raising to the tenth power the elements individually on the leading diagonal.

Recall that

P =

1 1

-1 -2

P * D.^10 * inv(P)

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

P = [1 1 ; -1 -2];

D = [1 0 ; 0 1024]

A10 = P * D * inv(P)

For 3x3 example see



Compare this with Matlab’s brute force:

>> A^10

ans =

-1022 -1023

2046 2047

Or page 494 Stroud Advanced.

Eigenvalue Decomposition To compute the Eigenvalues and the Eigenvectors

>> [V,D] = eig(A)

Singular Value Decomposition To compute the Singular Value Decomposition

of a matrix A

>> [U,D,V] = svd(A)

x^2-3x-2=0

r =

2

1

p =

1 -3 2

See Polynomials in Mathematics in MATLAB in Help

If using sym we get the actual polynomial eg x^2 +.. etc.

x^2 – 3x +2 = 0

(Eigen values.)

A Cell Array can be an array of arrays eg

clc;

b=ones(2,2)

1 1

1 1

A = magic(2)

1 3

4 2

Note the difference: eg

[A b]gives one concatenated array

1 3 1 1

4 2 1 1

whereas:

C={A, b}; is an array of arrays.

[pic]

X=C{1,1} gives the whole (first)array:

X = 1 3

4 2

X(2,2)-> 2

or C{1,1}(2,2) -> 2

columns 1 to 2 inclusive.

The whole row of such columns.

If the data in the cell array is numeric:

D = {4, 5, 6;

1, 2, 3};

Then we can convert it to an ‘ordinary’ array:

cell2num or something

-> E =

4 5 6

1 2 3

o We can also enter data by double-clicking on a cell here and…

…a separate cell editor opens up for that cell.

o Enter some numbers.

M =

[ 1]

[2x2 double]

[3x3 double]

[4x4 double]

[5x5 double]

[6x6 double]

[7x7 double]

[8x8 double]

ans =

1

ans =

1 3

4 2

ans =

8 1 6

3 5 7

4 9 2

structure

3 structures are created within the structure A.

Name is char.

bal is Double

We can also create the same structure as follows:

s(1).name = 'ed';

s(2).name = 'jo';

s(2).name = 'al';

cell array

As per usual the name of the m-file and of the function should be the same.

dy/dx = y

func.m

We have used @ to define a function handle which can then be used/called from the function as shown.

(Or we could explicitly define the function handle first eg f = @func and then call it like so:

ode45(f, [0,1], 1)

might need to clear all first here.)

dy/dt = y. -> y = e^t

Plot commands such as plot and meshgrid as distinct from symbolic plot function such as ezplot act upon a series of matrix data – usually x & y. In this case we need the element-wise dot operator eg X.^2

saddle.m

o Looks like Matlab should not be running? Close it if it is and start it from Excel. yes

o Best make them all cells lest text in excel become cells as it should but number doesn’t ie if we had to concatenate a row of text and a row of numbers. Make sure that they are consistent. We won’t get error message if not ! Click OK.

(Maybe make then not cells and import them separately.)

o Send data to Matlab.

o Give it a name.

(After a Spreadsheet Link EX function successfully executes as a worksheet formula, the cell contains the value 0 to indicate success.)

The address has quotes this time!

The matrix is returned from Matlab into the column whose top address is B1.

From the VBE First make sure that we have this reference.

Make that eds.m is saved.

Take care to save class before running.

Also use clear in case class remnants remain after error.

The class MUST be saved in a file with the same name – in this case Part.m.

0- argument constructor.

1- argument constructor.

Methods always have the first(extra)object argument. (This paramater could be called anything eg x.)and called with no arguments in this case like so:

p2.mulltTen()

The p2 is passed implicitly to obj!

.

So if we had a method using TWO parameters

eg function s = sumSq(obj,j) % Method

s = obj.i^2 * j^2;

end

then we would call it using ONE parameter eg p1.sumSq(2), the p1 being implicitly passed to obj. (Bit confusing!).

Having said all that we can call it using:

sumSq(p1,2) !

.

But we can use traditional notation:

p1.mulltTen();

p1.sumSq(2)

Gets the data using the handle to plot.

Belatedly plots the new (blue curve) data.

Use set to alter plots parameters AFTER the plot command.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download