46
MATLAB AND MATRICES Dan Witzner Hansen Email: [email protected]

Dan Witzner Hansen Email: [email protected]. Interactive System Data processing Programming Visualization Basic element is an array Easy vector

  • View
    218

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

MATLAB AND MATRICES

Dan Witzner HansenEmail:[email protected]

Page 2: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

MATLAB - STUDENT EDITION!!!!

Page 3: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

WHY USE MATLAB? Interactive System

Data processing Programming Visualization

Basic element is an array Easy vector and matrix manipulation Lots of built in functions and code libraries Implicit loops for arrays

Many preexisting functions Filtering, converting, sorting, finding, means,

minimum.

Lots of online material

Page 4: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

WHY IS MATLAB RELEVANT FOR YOU? Avoid using too many libraries (and convert between

formats)

Easy to see the connection between code and mathematics (Matrix of doubles is the primitive type)

Good plotting facilities (also for other courses)

Programming is a little different from what you have tried before – in some sense a little more primitive :D

Page 5: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

WHY IS LINEAR ALGEBRA INTERESTING? It has many applications in many

diverse fields. (computer graphics, chemistry, biology, differential equations, economics, business, ...)

It strikes a nice balance between computation and theory.

Essential the course

Page 6: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

WHAT IS A MATRIX?

A matrix is a set of elements, organized into rows and columns

rows

columns

mnm

n

aa

aaa

A

1

11111

Page 7: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

MATRIX EXAMPLES

mnm

n

aa

aaa

A

1

11111

Patient

Gender,age,height, weight

Page 8: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

VECTOR

nn

T Raaaa 121 ),...,,(

),( a 21 aa

Column vector (default):

12

1

n

n

R

a

a

a

a

Row vector:

Page 9: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

VECTOR OPERATORS

Addition: Multiplication with scalar

Multiplication : Inner product (“row times column”)

Outer product (“column times row”)

)( 2211 nn

n

iii

T yxyxyxyxyx

),,( 2211 nn yxyxyxyx vw

V+w

Raaxaxxxaax ),,(),( 2121 v

av

yxT =

y1x1 y1x2 K y1xny2x1 y2x2 y2xn

ymx1 ymx2 ymxn

⎢ ⎢ ⎢ ⎢

⎥ ⎥ ⎥ ⎥

xyyx TT

TT xyyx

Page 10: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

MATLAB: SCALARS, VECTORS

>> a = 5;>> b = [1 2 3 2 1];>> c = [1:0.25:2]’

c =1.001.251.501.752.00

>> c(5) = -10c = -10.00

1.251.501.752.00

>> a*b>> c = [5 10 15 10 5]

>> a-b

ans = [4 8 12 8 4]

Page 11: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

NORM / LENGTH AND ORTHOGONALITY

222

21x n

T xxxxx >> x = [2 -5];>> norm(x)ans = 5.3852

)90cos(0 oT yx

2-Norm:

Orthogonal:

Orthonormal:

Orthogonal and ||x||=||y||=1

Page 12: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

LOOK AT EXERCISE 1

Page 13: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

MATRIX: BASIC OPERATIONS

Addition, Subtraction, Multiplication

hdgc

fbea

hg

fe

dc

ba

hdgc

fbea

hg

fe

dc

ba

dhcfdgce

bhafbgae

hg

fe

dc

ba

Page 14: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

OPERATORS AND MATRIX OPERATIONS+ - addition, subtraction

• / ^ matrix multiplication, division, power

* [ 2 x 3] * [3 x 2] = [2 x 2]

[ ] define matrix

.* ./ .^ array multiplication, division, power(arrays must be the same size)

n’ transpose, complex conjugate

; separate rows, non-echo end of line.

Page 15: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

ENTERING DATA - 2D MATRICES

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

c = 1 2 34 5 67 8 9

Page 16: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

USEFUL MATRIX INITIALIZERS

zeros(n,m) an n x m matrix of zeros

ones(n,m) an n x m matrix of ones

rand(n,m) an n x m matrix of uniformly distributed numbers

randn(n,m) an n x m matrix of normally distributed numbers

Page 17: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

SIMPLE OPERATORS IN MATLAB

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

Res = c*d’;

M = c.*d;

Add = c+d;

Page 18: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

OPERATORS AND MATRIX OPERATIONS

: “all elements” of row, column or between 2 numbers.

( ) specify elements of a defined vector/matrix

/ A/B = (B'\A')'B'\A

^ z = x^y, x or y must be a scalar.

X = A\B is the solution to the equation A*X = B (more about this next week)

Page 19: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

INITIALIZING MATRICES

>> A = zeros (5,5)>> c = [5 10 15 10 5]

>> A[1,:] = c;

>> diag([1 2 3 4])1 0 0 00 2 0 00 0 3 00 0 0 4

>> eye(3)1 0 00 1 00 0 1

Page 20: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

ACCESSING DATA - 2D ARRAYS

>> d = c(1:2,2:3)d =

4 75 8

>> e = [d d]

e = 4 7 4 75 8 5 8

>> f = [d; d]

f =4 75 84 75 8

Extracting part of a matrix

( ) specify elements of an array , separates dimension : entire row or column

Combining Arrays

Horizontal concatenation no punctuation

vertical concatenation; separates arrays

Vectors of indices

Page 21: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

ACCESSING DATA - 2D ARRAYS>> x = [3 2 0 1 5 4];>> minx = min(x)

minx = 0

>> y = sort(x)

y =0 1 2 3 4 5

>> find(x)

ans =1 2 4 5 6

>> i4 = find(x==4)

i4 =6

Functions for extracting data:

min, max, mean, median, sort

find

Page 22: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

ARRAY VERSUS MATRIX OPERATIONS

>> a = [1 2 3 4 5]; >> b = a;>>>> c = a.*bc =

1 4 9 16 25

>> d = a*b’d =

55

Array operations include animplicit loop through theentire array.

The operation is repeated foreach element in the array.

The matrix operation does thelinear algebra operation forthe matrices.

Page 23: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

SOME PREDEFINED VARIABLES

pi 3.14159265

i,j sqrt(-1) imaginary unit

eps 2.2204e-016 (small number, can also be set to a number)

inf infinity (from 1/0)

nan not-a-number (from 0/0)

Page 24: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

THE DOT-M FILE

Commands can be entered one at a time on the command line within MATLAB

A series of commands (functions) can be entered into a dot-M file (name.m).

To run the set of command, just type the name of the dot-M file: dot-M file namet.m execute commands >> name [a,b,c,d] = someFunction(x,y,z);

Page 25: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

THE SHAPE OF MATLAB PROGRAM>>[A,B]= example1('Example 1',0.1,0,5,0.2,0,5);>> help example1

% example1.m% Comment lines start with the percent sign% This is an example function which takes 3 parameters modelname is a string with the % name of the model to be used in the title line. dx and dy are the intervals for the % x and y variables, which range in value from from xmin to xmax or ymin to ymax.

function [Value1,Value2]=example1(modelname,dx,xmin,xmax,dy,ymin,ymax);

% Define x and yx = [xmin:dx:xmax];y = [ymin:dy:ymax];

% Make a mesh out of x and y

Call to the example1 function

Comments and help file information

Definition of a function same name as the filenameNot always needed – scripts also possible

Page 26: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

SOME STARTER TIPS MATLAB is case sensitive:

a and A are different. Use a ; at the end of the line to stop

commands from echoing to the screen Use keys to scroll through previously

entered commands and rerun. Help / helpwin will tell you how to use a

function and what it does. (e.g. >> help plot or >>help ops). Help on toolbar

Page 27: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

BASICS OF PROGRAMMING IN MATLAB

n = 5for i = 1:n a(i) = i + 2;end

test = 1;cnt = 1;while (test ~= 0) b(cnt) = 1/test; test = test - 0.1;

cnt = cnt + 1;end

For Loopdefault increments by 1can define other incrementfor i = 1:0.1:n

While Loopcontinues as long as boolean expression is true.

Page 28: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

BASICS OF PROGRAMMING IN MATLAB

if a == 0b = a;

elseb = 1/a;

end

if and(x > xmin,x < xmax) disp(‘x is within limits’);elseif (x > xmax) disp(‘x is too large’);elseif (x < xmin) disp(‘x is too small’);end

If - elseif - elsecan have several sequentialboolean tests

can use both else and elseifor just one.

Page 29: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

SAVING DATA

save creates matlab.mat with all variables in workspace

save fname creates fname.mat with all variables

save fname var1 var2 saves only variables var1 & var2

save fname.txt var1 -ascii -tabs -double saves var1 as a table of ASCII numbers called fname.txt

Page 30: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

INPUTTING DATA FROM FILE

load file of ascii data in columns>> load filenamedata loaded into variable filename>> A = load(‘filename’);data loaded into variable A

fscanf formatted ascii datafread binary data filefopen open files (for fscanf, fread)fclose closes files

Page 31: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

PLOTTING

Page 32: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

PLOTTING - GENERAL COMMANDS

figuresubplottitleXlabel,ylabelZlabeltextaxiscolorbarshadingsetgcagcf

creates a new figure windowdefines multiple plots on a single pagedefines plot title text X,y,x axes label text

puts text at specified coordinatesdefines the axis limitscreates a colorbardefines type of shading (faceted, flat, interp)use to define properties of the axis or figurereturns handle to current plot axisreturns handle to current figure

Page 33: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

LOTS OF 2D GRAPHICS FUNCTIONS

Plotloglogsemilogxsemilogybarerrorbarfplothistpolarrosestairs

linear plot of lines, points or symbolslog-log scale plotlog (x-axis) - linear (y-axis) plotlog (y-axis) - linear (x-axis) plotLinear plot with error barsFunction plothistogrampolar coordinate plotangular histogram plotstairstep plot

Page 34: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

3D GRAPHICS FUNCTIONS

plot3fill3contour,contour3pcolorquiver, quiver3stream, stream3mesh, meshc, meshz

surf, surfc, surfl

surfnormcylinder, sphere

Plot lines and points in 3D space Filled 3D polygons in 3D spacecontour data in 2D or 3D spacecheckerboard color plot in 2Dvector plot in 2D or 3DStream lines in 2D or 3DMesh surface in 3D, with contours

or zero plane.Shaded surface in 3DDisplay surface normal vectors.Generate a cylinder or sphere.

Page 35: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

EXAMPLE: DOT-M FILES, FUNCTIONS, PLOTTING

Cosine Curve

Page 36: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

EXAMPLE: DOT-M FILES, FUNCTIONS, PLOTTING

>> example1('Example 1',0.1,0,5,0.2,0,5);>> help example1

% example1.m% Comment lines start with the percent sign% This is an example function which takes 3 parameters modelname is a string with the % name of the model to be used in the title line. dx and dy are the intervals for the % x and y variables, which range in value from from xmin to xmax or ymin to ymax.

function example1(modelname,dx,xmin,xmax,dy,ymin,ymax);

% Define x and yx = [xmin:dx:xmax];y = [ymin:dy:ymax];

% Make a mesh out of x and y[X,Y] = meshgrid(x,y); % takes vectors and repeats x for every y and y for every x.

% Define a function for every x, y pairZ = sin(X).*cos(Y);whos X Y Z

Page 37: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

EXAMPLE: DOT-M FILES, FUNCTIONS, PLOTTINGminz = min(min(Z));maxz = max(max(Z));

save ex1dat X Y Z % saves variables in binary matlab format

% Plottingfigure; % opens a new figure window.subplot(2,3,1) % 6 plots in figure split into 2 rows and columns % 1- first plot is in top-left plot(X(1,:),Z(1,:),'r') % plot all the points in the % first column as a red line

% (also b, g, y, c, m, k, w).title(['Plot 1: ' modelname]); xlabel('X'); ylabel('Z'); grid; % Plots grid linesaxis([xmin-dx xmax+dx minz maxz]);

Page 38: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

EXAMPLE: DOT-M FILES, FUNCTIONS, PLOTTING

subplot(2,3,2)plot(Y(:,2),Z(:,2),'gx'); % plots points as green x's

% (type 'help plot' for full list).vlab = input(‘Enter label: ‘,’s’); % get data from command line hold on; % allows you to overlay more % symbols, lines etc...plot(Y(:,4),Z(:,4),'ro'); plot(Y(:,6),Z(:,6),'m*'); title('Plot 2: plot symbols'); text(2,0.5,vlab); % add text labelsxlabel('Y'); ylabel('Z'); grid;axis([ymin-dy ymax+dy minz maxz]);

subplot(2,3,3)plot(Y,Z,'.-'); % plot all rows of X versus all rows of Z % -- dashed line, also -solid, : dotted, -.dash-dot % can also combine symbols and line 'o-;title('Plot 3: whole array'); xlabel('Y'); ylabel('Z'); grid;axis([ymin-2*dy ymax+2*dy 2*minz 2*maxz]);

Page 39: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

EXAMPLE: DOT-M FILES, FUNCTIONS, PLOTTING

subplot(2,3,4)pcolor(X,Y,Z);shading flat; colorbar('horiz');title('Plot 4: pcolor'); xlabel('X'); ylabel('Y');

subplot(2,3,5)meshc(X,Y,Z);shading flat; colorbar('horiz');title('Plot 5: meshc'); xlabel('X'); ylabel('Y'); zlabel('Z')

subplot(2,3,6)surfl(X,Y,Z);shading interp; colorbar;set(gca,'Zlim',[-2 2]);view(15,20);title('Plot 6: surfl'); xlabel('X'); ylabel('Y'); zlabel('Z')

Page 40: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

EXAMPLE: DOT-M FILES, FUNCTIONS, PLOTTING

% Save data to ascii file as column data[nx,ny] = size(X);X = reshape(X,nx*ny,1);Y = reshape(Y,nx*ny,1);Z = reshape(Z,nx*ny,1);

dat = [X Y Z];keyboard;

save ex1.asc dat -ascii

Cosine Curve

Page 41: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

SIMPLE?figure(1) ; clf t = linspace(0, 2*pi, 512) ; [u,v] = meshgrid(t) ; a = -0.2 ; b = .5 ; c = .1 ; n = 2 ; x = (a*(1-v/(2*pi)) .* (1+cos(u)) + c) .* cos(n*v) ; y = (a*(1-v/(2*pi)) .* (1+cos(u)) + c) .* sin(n*v) ; z = b*v/(2*pi) + a*(1-v/(2*pi)) .* sin(u) ; surf(x,y,z,y) shading interp axis off axis equal colormap(hsv(1024)) material shiny lighting gouraud lightangle(80, -40) lightangle(-90, 60) view([-150 10])

Page 42: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

SOME OTHER USEFUL COMMANDS

who lists all or specified variables currently defined

whos same as who, but also gives dimensions of arrays, size in bytes and type (e.g. double, complex)

clear clears all or specified variable from memory

keyboard within a dot-M file gives command control to the keyboard. Type return to continue.

ginput(N) Get N mouse clicks

Page 43: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

IMAGES, PLOTS & MOUSE INPUTS

Reading and saving images easy (imread, imshow)

Often want to draw on top of an image Hold (on/off)

>> I = imread(‘GroundFloor.bmp’)>> figure(1)>> imshow(I);>> [X,Y,Z] = ginput(2)>> hold on>> plot(X,Y,’rx’,’MarkerSize’,10,’LineWidth’,3)>> hold off

Page 44: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

LEARNING MORE

Remember the help / helpwin commands MATLAB help pages:

describe how to use functions and gives examples

provides theory behind more complex functions Getting Started MATLAB Functions Listed by Category MATLAB Functions Listed Alphabetically

MATLAB Reference Guide, User’s Guide same as help pages, but in print -- sometimes

nice to flip through when you’re not sure what you’re looking for

Page 45: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

YOUR FIRST ASSIGNMENT

Try to get Matlab running Take a look at a Matlab primer Watch some movies – if you have not

done so already Next week:

More linear algebra DON’T LET THAT DISCURAGE YOU

Page 46: Dan Witzner Hansen Email: witzner@itu.dk.  Interactive System  Data processing  Programming  Visualization  Basic element is an array  Easy vector

MORE QUESTIONS?

Feel free to e-mail me at any time