55
MATLAB Matrix Laboratory

M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page For MATLAB, select chap01b.ppt,

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

Page 1: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

MATLAB

Matrix Laboratory

Page 3: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Programming

The ideal style of programming is structuredstructured

• Break down a larger goal into tasks• Develop a modulemodule for each task• A module has a single entrance and exit• Modules are reusable

Page 4: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Use MATLAB to solve a problem

• State the problem clearly

• Describe the Input/Output (I/O)

• Algorithm - Numerical Method

• Develop a MATLAB program

• Debugging and Testing

• Documentation

If needed, work the problem by hand

Page 5: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Compiler and Program Execution

Computer Program Compiler

Machine language program

Link/Load

Execute

input

output

executionadinglinking/loncompilatio

MATLAB Execution

Interactive environment - does not require formal compilation, linking/loading, and execution

Scripts - develop and execute m-files that contain MATLAB commands

Page 6: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Important!

You must include commentscomments in your programs you turn in - otherwise we will have great difficulty knowing what you are thinking and doing. You will have

difficulty knowing what you were doing if you need to reuse the programs.

Page 7: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Command Window - enter commands and data - print results

Graphics Window - display plots and graphs

Edit Window - create and modify m-files

MATLAB’s 3 Windows

Page 8: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Two simple MATLAB programs (also called scripts)

Filename: lec2a.m

% Find sum of 1 to b% Comments begin with “%”% cd y:\cven302\clear allsum = 0;b = input('what is the value of b? ')for i = 1 : b sum = sum + iend

Need extension .m called m-file

Page 9: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Filename: lec2b.m

% plot 1/x v.s. tanh x

clca = linspace(0,5);f = 1./a;g = tanh(a);plot(a,f,'-', a, g,'--')axis([0 3 0 2])xlabel ('x')ylabel ('y')title ('Plot 1/x and tanh x')text(0.7, 1.6, '1/x')text(2, 1.1, 'tanh x')

Page 10: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Now we have seen Command Window, Graphics Window, and Edit Window

There is another window which is very useful:the Help Window

You can also type help in Commend Window

e.g.,

help input

Page 11: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» help input

INPUT Prompt for user input. R = INPUT('How many apples') gives the user the prompt in the text string and then waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix. R = INPUT('What is your name','s') gives the prompt in the text string and waits for character string input. The typed input is not evaluated; the characters are simply returned as a MATLAB string. See also KEYBOARD.

Page 12: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

MATLAB’s basic component is a matrixi.e., all variables are treated as matrices

All operations are vectorized (optimized for vector use)

Loops run much slower in MATLAB than in Fortran (not a vector operation)

Page 13: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Scalar, vector, and matrix

Scalar: k = 511 matrix

Matrix:

8642

9753

4321

a

m n matrix

m rows (m = 3)n columns (n = 4)

2

3

1

c 4321b

14 matrix, or a row vector

Vector:

31 matrix, or a column vector

Page 14: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Variable

• may consist up to 31 characters

• starting with a letter and followed by any combination of letters, digits, and underscores (Variable names must start with a letter)

• punctuation marks and spaces should not be included

e.g., CVEN_302, TIME, Time, time, velocity, force_x, force_y

Page 15: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

• All numbers are double precision

• Text is stored as arrays of characters

• You don’t have to declare the type of data (defined when running)

• Variables are case sensitive

Data Type

e.g., CVEN_302, TIME, Time, time, velocity, force_x, force_y

Page 16: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Arithmetic operation of scalars

Addition: a+b subtraction: a-bmultiplication: a*b division: a/bexponentiation: a^b= ab

abs(x) : absolute value sqrt(x) : square root = x^(1/2)sin(x) : sine asin(x) : inverse sinesinh(x) : hyperbolic sine asinh(x) : inverse hyperbolic sinelog(x) : natural logarithm log10(x) : common logarithmexp(x) : exponental: ex (e = 2.7183….)

Elementary math functions

Page 17: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» a = 5;» b = 3;» a*bans = 15» d = ans * 3d = 45» e = ans * 3;» ee = 45» a^2ans = 25

» a/bans = 1.6667» format long» a/bans = 1.66666666666667» format short» a/bans = 1.6667

Page 18: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» exp(2)ans = 7.3891» 10^2ans = 100» log(100)ans = 4.6052» log10(100)ans = 2» pians = 3.1416

; - result not displayedformat long - 15 digitsformat short - 5 digitsans - result from previous calculationpi -

Ctrl-c : terminate a running program

2e

100ln

100log

Page 19: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Array Operations

• An array operation is performed element-by-An array operation is performed element-by-element - Need “element - Need “..” in front of the operator” in front of the operator

B(5);A(5) C(5)

B(4);A(4) C(4)

B(3);A(3) C(3)

B(2);A(2) C(2)

B(1);A(1) C(1)

MATLAB: C = AMATLAB: C = A..B;B;

Page 20: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Arithmetic operation of Arrays

Addition: a+b subtraction: a-bmultiplication: a.*b division: a./bexponentiation: a.^b = ab

Page 21: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

MATLAB variables and matrix operation

2

3

1

c 654b

» b = [4 5 6]b = 4 5 6» c = [1 3 2]c = 1 3 2

» c = [1; 3; 2]c = 1 3 2» d = c'd = 1 3 2

- transpose

; - a new line

Page 22: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» b * cans = 31» b.*dans = 4 15 12» b./dans = 4.0000 1.6667 3.0000» f = [b; d; [3 6 8]]f = 4 5 6 1 3 2 3 6 8

2

3

1

c 231d

654b

b.*d = [4*1 5*3 6*2]b./d = [4/1 5/3 6/2]

bd[3 6 8]

» f(2,3)ans = 2» size(f)

size - size of a matrix

Page 23: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Matrix Operation (conti.)

497 ; 321 yx

497321 yxz

497

321 ; yxu

s = [1 2 3 4; 5 6 7 8]t = [1 2 3 4.... 5 6 7 8]

continue

Page 24: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Colon Operator

Creating new matrices from an existing matrix

C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]

F = C(:, 2:3) = [2,5; 0,1; 2,-1; 1,4]

E = C(2:3,:) = [-1 0 1; 3 2 -1]

G = C(3:4,1:2) = [3,2; 0,1]

410

123

101

521

C

123

101E

41

12

10

52

F

10

23G

all columns

rows 2 to 3

Page 25: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» x = 1:10x = 1 2 3 4 5 6 7 8 9 10» t = 1 : 2 : 10t = 1 3 5 7 9» k = 5:-1:-3k = 5 4 3 2 1 0 -1 -2 -3

a : step : b gives number from a to b with the specified step between elementsstep = 1 if not specified

Page 26: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

What if the step is not easy to calculate, or is an odd number?

y = linspace (a, b, n_pts)

» y = linspace (0, 1, 4)y = 0 0.3333 0.6667 1.0000

2 end points are included in n_pts.

y = linspace (0,1)

a number of 100 for n_pts is assigned.

Page 27: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Some useful special matrices

» eye (3)ans = 1 0 0 0 1 0 0 0 1» ones (3)ans = 1 1 1 1 1 1 1 1 1» ones (1,4)ans = 1 1 1 1

» zeros (2,3)ans = 0 0 0 0 0 0

eye (m,n) eye (n)ones (m,n) ones (n) zeros (m,n) zeros (n)

Page 28: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Plotting

plot (x, y) plot(x1, y1, x2, y2)

plot (x, y, ‘color symbol line style’)

» x = linspace(0, 2*pi);» y = sin (x);» z = cos (x);» plot (x, y)» plot (x, y, x, z)» figure (2)» plot (x, y, 'r o -'); grid on» hold on» plot (x, z, 'b x :')

red, circle, solid

blue, x-mark, dotted

figure or figure (#) : open a figure

try help plotadd grids

try grid off

Page 29: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» xlabel ('x')» ylabel ('y')» title ('sine and cosine')» text (2, 1, 'This is a sine fuction')» axis ([0 2*pi -2 2])» hold off

xlabel (‘ label ‘) ylabel (‘ label ‘)title (‘ title of the plot ‘)text ( x_location, y_location, ‘ text ‘)axis ([ x_min x_max y_min y_max ])

Plotting (continue)

- text string

hold on: hold the plots to avoid overwriting

Page 30: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

subplot ( m, n, figure number ) - break the figure window into m by n small figures, and plot the specified figure

Plotting (continue)

» figure» subplot (3, 2, 1)» plot (x, y)» subplot (3, 2, 2)» plot (x, z)» subplot (3, 2, 4)» plot (x, y-z)

1 2

3 4

5 6

Page 31: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

semilogx (x, y) logarithmic scales for the x axis.

semilogy (x, y) logarithmic scales for the y axis.

loglog (x, y) logarithmic scales for the x and y axes

x = 10.^[-1:0.1:2];y = exp(x);figure(1)semilogy(x,y,':^')

figure(2)loglog(x,y,'-s')grid on

Page 32: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

More control on plotting

get(H) get object properties

set(H,'PropertyName',PropertyValue,...)

set object properties

figure(2)h = loglog(x,y,'-sr')grid on

get(h)set(h, 'LineWidth',2)set(h, 'MarkerFaceColor', [0 0 1])

Page 33: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

who list of current variablesclc clear the command windowclf clear the graphical windows clear x clear the variable xclear all clear all variablesclose close the current figureclose all close all figurescd y:\cven302\ change directorydir list all fileswhat list all m-filesCTRL-C Abort

semicolons (;) at the end of line: Calculation results will not be displaced on the command window

Some useful commands

Page 34: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Initializing Variables

• Explicitly list the values• reads from a data file• uses the colon “:” operator• reads from the keyboard

Page 35: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Input and output (I/O)

a = input (‘ enter a value or string ‘) - wait for input from the keyboard

load file_name- input an existing data file (ASCII format)

diary file_name- save anything in the Command Window

diary off

save file_name variable(s) -ascii- save the data of the variable(s) to a file in ASCII format

You may need to go to certain directory before loading and/or saving files

Page 36: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» diary tmp.dat» a = [ 1 2 3; 4 5 6]a = 1 2 3 4 5 6» save a_file.dat a -ascii» load a_file.dat» b = a_fileb = 1 2 3 4 5 6» d = input ('give a value to d: ')give a value to d: 5d = 5» diary off

Save in the tmp.dat file

Page 37: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

M-Files: Scripts and Functions

• You can create and save code in text files using MATLAB Editor/Debugger or other text editors (called m-files since the ending must be .m)

• M-file is an ASCII text file similar to FORTRAN or C source codes ( computer programs)

• A script can be executed by typing the file name, or using the “run” command

Page 38: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Functions

distinguished from the script that the first line is of the form

function x = function_name (input arguments)

function [x, y] = function_name (input arguments)

A function has to be stored as a stand-along file ended with “.m”. The name of the function is usually (but not necessary) the same as the name of the file.

Difference between scripts and functions

Scripts share variables with the main workspaceFunctions do not

Page 39: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

function t = trap_ex(a, b)t = (b - a) * (a^(-3) + b^(-3)) / 2;

Approximate integral f(x) = 1/x3 using basic trapezoid rule

File name: trap_ex.m

» y = trap_ex (1, 3)y = 1.0370»

dxx

yb

a3

1

Page 40: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

bfafab

I

2

Trapezoidal rule

a b

f(a) f(b)

height average width I

Page 41: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

function t = trap_ex2(a, b, step)dx = (b - a)/step;x1 = a;t = 0;for i = 1 : step x1 = a + (i-1)*dx; x2 = a + i*dx; t = t + (x2 - x1) * (x1^(-3) + x2^(-3)) / 2;end

File name: trap_ex2.m

Approximate integral f(x) = 1/x3 using basic trapezoid rule with n steps used

Page 42: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

» y = trap_ex2 (1,3,1)y = 1.0370» y = trap_ex2 (1,3,2)y = 0.6435» y = trap_ex2 (1,3,100)y = 0.4445» y = trap_ex2 (1,3,1000)y = 0.4444» format long» y = trap_ex2 (1,3,1000)y = 0.44444543209743 Exact solution = 0.444444444444 ….

» x1??? Undefined function or variable 'x1'.

Why?

Page 43: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

feval - evaluate function specified by string

function y = my_func(x)% function 1/x^3y = x.^(-3);

function q = basic_trap(f, a, b)% trapezoid rule with input function fya = feval(f, a);yb = feval(f, b);q = (b - a)* (ya + yb)/2;

my_func.m

basic_trap.m

» y = basic_trap ('my_func', 1,3)y = 1.0370

» feval('my_func', 1)ans = 1

Page 44: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Decision Making: Control Flow

(a) For Loops

(b) While Loops

(c) If-Else Structures

Page 45: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

z = 0;for i = 1:10 y(11-i) = i; z = z+i;end

For Loops

for x = arraycommands

end

» yy = 10 9 8 7 6 5 4 3 2 1» disp(z) 55

Without this line you will get:Warning: Reference to uninitialized variable z.

disp (x) - display the value of x

Page 46: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Filename: lec2a.m

% Find sum of 1 to b% Comments begin with “%”% cd y:\cven302\clear allsum = 0;b = input('what is the value of b? ')for i = 1 : b sum = sum + iend

Page 47: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

While Loops

while expressioncommands

end

eps = 1;count = 0;while (1+eps) > 1 eps = eps/2; count = count + 1;endeps = eps*2display(count-1)

Floating point relative accuracy

(is true)

Determining machine epsilon

52 digits in double precision (64 bit)

eps = 2.2204e-016ans = 52

Page 48: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Floating point

epBdddddN 4321.

a number digit base

exponent

d1 0: normalized floating-point system

Single precision: 32 bits (23 for digit, 8 for exponent, 1for sign

Double precision: 64 bits (52, 11, 1)

Page 49: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

What if we omit this operation?

Use “break” to terminate while and for loops prematurely (or set a limit in while loops)

The loop becomes an “infinite loop” because the statement is always true.

eps = 1;count = 0;while (1+eps) > 1 eps = eps/2; count = count + 1;endeps = eps*2display(count-1)

eps = 1;count = 0;while (1+eps) > 1 & count < 100 eps = eps/2; count = count + 1;endeps = eps*2display(count)

Page 50: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

If-Else Structures

if expression (is true)commands

end

if expression 1commands 1

elseif expression 2commands 2

elseif expression 3commands 3::

else commands n

end

if expressioncommands 1

elsecommands 2

end

Page 51: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Relational Operators

< less than<= less than or equal to> greater than>= greater than or equal to== equal to~= not equal to

Logical Operators

& and| or~ not

Page 52: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

eps = 1;count = 0;while (1+eps) > 1 eps = eps/2; count = count + 1; if count > 100 break endendeps = eps*2display(count)

eps = 1;count = 0;while (1+eps) > 1 & count < 100 eps = eps/2; count = count + 1;endeps = eps*2display(count)

Page 53: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

a = input('what is the value of input data? ')if a > 0 sign = 1;elseif a < 0 sign = -1;else sign = 0;end

disp(sign)

Page 54: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

print - print out current figure

print -djpeg filename - save current figure in jpeg format

print -djpeg# filename - save current figure in jpeg format with # (resolution level) between 0 and 100 (default 75)

print -dtiff filename - save current figure in tiff format

print -dpsc filename - save current figure in color PostScript format

Print figures to image files

See help print for more

Page 55: M ATLAB Matrix Laboratory. Internet Resources: Dr. H-C Chen’s CVEN 302 Web Page  For MATLAB, select chap01b.ppt,

Filename: lec2b.m% plot 1/x v.s. tanh x

clca = linspace(0,5);f = 1./a;g = tanh(a);plot(a,f,'-', a, g,'--')axis([0 3 0 2])xlabel ('x')ylabel ('y')title ('Plot 1/x and tanh x')text(0.7, 1.6, '1/x')text(2, 1.1, 'tanh x')

» cd y:\cven302» print -djpeg myfigure1» print -djpeg100 myfigure2