Download presentation
Presentation is loading. Please wait.
Published byAdam Nelson Modified over 9 years ago
1
Introduction to MATLAB D. Heslop and M. Schulz
2
Why MATLAB? If calculations have to be repeated many times a computer is the ideal tool for such boring task MATLAB combines the power of a classical programming language for computation with numerous extra tools, especially for visualization MATLAB stands for MATrix LABoratory The system was originally designed to make matrix computation particularly easy
3
Starting MATLAB
4
Display Windows
5
Calculations at the Command Line »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = 1.5708 »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = 1.5708 Results assigned to “ans” if name not specified () parentheses for function inputs Semicolon suppresses screen output MATLAB as a calculator Assigning Variables » -5/(4.8+5.32)^2 ans = -0.0488 » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = 6.1230e-017 » exp(acos(0.3)) ans = 3.5470 » -5/(4.8+5.32)^2 ans = -0.0488 » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = 6.1230e-017 » exp(acos(0.3)) ans = 3.5470
6
Algebraic and Assignment Operators Addition + a+b Subtraction - a-b Multiplication * a*b Division /a/b Power ^a^b Assignment =a=b (assign b to a )
7
Variables in MATLAB Variable names: –must start with a letter –may contain only letters, digits, and the underscore “_” –are case sensitive, i.e. one & OnE are different variables –must differ in the first 63 characters Assignment statement: –Variable = number; –Variable = expression; Example: >> a = 1234; >> a = 1234 a = 1234 NOTE: when a semi-colon ”;” is placed at the end of a command, the result is not displayed.
8
Pre-Defined Variables ans default variable name for the result pi = 3.1415926………… i or j imaginary unit ( i = j = square root of -1) Inf or inf infinity NaN or nan not-a-number eps smallest difference between 2 numbers (2.2204e-016) realmin smallest usable positive real number (2.2251e-308) realmax largest usable positive real number (1.7977e+308)
9
Commands Involving Variables who lists the names of defined variables whos lists the names and sizes of defined variables clear clears all variables clear name clears the variable name clc clear command window
10
Getting Help MATLAB has a very comprehensive online help system help – lists all the help topic help topic – provides help for the specified topic help elfun – lists available elementary functions help command – provides help for the specified command help sin – usage of the sine function lookfor keyword – Search all commands for keyword demo – Lists tutorial demos Note: Use doc instead of help for browser-type help interface
11
MATLAB Matrices MATLAB treats all variables as matrices. A vector (or array) is a special form of a matrix and contains only one row OR one column. A scalar is a matrix with only one row AND one column.
12
MATLAB Matrices A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows: » a = 23 a = 23
13
MATLAB Matrices A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas): » rowvec = [12, 14, 63] rowvec = 12 14 63 For simplicity, the commas may be skipped (note spaces): » rowvec = [12 14 63] rowvec = 12 14 63 Use square brackets [ ]
14
MATLAB Matrices A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons): » colvec = [13; 45; -2] colvec = 13 45 -2
15
MATLAB Matrices A matrix can be created in MATLAB as follows (note spaces AND semicolons): » matrix = [1 2 3; 4 5 6; 7 8 9] matrix = 1 2 3 4 5 6 7 8 9 Row separator semicolon (;) Column separator space / comma (,)
16
The Matrix in MATLAB 410162 81.29425 7.257111 00.54556 238313010 1 2 Rows (m) 3 4 5 Columns (n) 1 2 3 4 5 A = A (2,4) Rectangular Matrix: Scalar:1-by-1 array Vector:m-by-1 array 1-by-n array Matrix:m-by-n array
17
Extracting a Sub-Matrix A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is: sub_matrix = matrix(r1:r2,c1:c2); r1, r2 beginning and ending rows c1, c2 beginning and ending columns
18
410162 81.29425 7.257111 00.54556 238313010 1234512345 1 2 3 4 5 A = A(3,1) A(1:5,5) A(:,5) A(4:5,2:3) Sub-Matrices in MATLAB
19
Addressing Vector Elements A vector element is addressed by an integer index enclosed in parentheses Example: >> x=[10 20 30 40 50 60]; >> x(3) ans = 30 Note: MATLAB index starts at 1 3 rd element of vector x
20
Addressing Vector Elements The colon notation may be used to address a block of elements: (start : increment : end) start is the starting index increment is the amount to add to each successive index end is the ending index A shortened format (start : end) may be used if increment is 1 Example: >> x=[10 20 30 40 50 60]; >> x(1:2:6) ans = 10 3050
21
Useful Commands for Vectors x = start:end create row vector x starting with start, counting by one, ending at end x = start:increment:end create row vector x starting with start, counting by increment, ending at or before end x = linspace(start,end,number) create row vector x starting with start, ending at end, having number elements length(x) returns the length of vector x y = x’ transpose of vector x
22
Scalar-Matrix Operations For addition, subtraction, multiplication, and division of a matrix by a scalar, the operation is applied to all elements of the matrix Example: >> A = [ 1 2; 3 4] A = 1 2 3 4 >> B = 2*A – 1 B = 1 3 5 7 Each element in the matrix A is multiplied by 2, then subtracted by 1
23
Element-by-Element Operations For element-wise multiplication, division and exponentiation of matrices the corresponding operator must be preceded by a dot Example: >> x = [ 1 2 3 ]; >> y = [ 4 5 6 ]; >> z = x. * y z = 4 10 18 Each element in x is multiplied by the corresponding element in y
24
Element-by-Element Operations OperationAlgebraic FormMATLAB Additiona + b Subtractiona – b Multiplicationa ∙ ba.* b Division a b a./ b Exponentiationabab a.^ b Note: Matrix addition and subtraction is element-wise by definition
25
Useful Commands for Matrices zeros(n) zeros(m,n) ones(n) ones(m,n) size (A) length(A) returns an n x n matrix of zeros returns an m x n matrix of zeros returns an n x n matrix of ones returns an m x n matrix of ones for an m x n matrix A, returns the row vector [ m,n ] containing the number of rows and columns in matrix returns the larger of the number of rows or columns in A
26
More Matrix Commands TransposeB = A’ Identity Matrixeye(n) returns an n x n identity matrix eye(m,n) returns an m x n matrix with ones on the main diagonal and zeros elsewhere. Addition and subtractionC = A + B C = A – B Scalar Multiplication B = A, where is a scalar. Matrix MultiplicationC = A*B Matrix InverseB = inv(A), A must be a square matrix in this case. rank (A) returns the rank of the matrix A. Matrix PowersB = A.^2 squares each element in the matrix C = A * A computes A*A, and A must be a square matrix. Determinantdet (A), and A must be a square matrix. A, B, C are matrices, and m, n, are scalars.
27
»w=[1 2;3 4] + 5 w = 6 7 8 9 »x = 1:5 x = 1 2 3 4 5 »y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 »z = ones(2,4) z = 1 1 1 1 »w=[1 2;3 4] + 5 w = 6 7 8 9 »x = 1:5 x = 1 2 3 4 5 »y = 2:-0.5:0 y = 2.0000 1.5000 1.0000 0.5000 0 »z = ones(2,4) z = 1 1 1 1 Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices Test yourself…
28
Deleting Columns and Rows in a Matrix >> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A(:,2)=[] A = 1 3 4 6 7 9 >> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A(:,2)=[] A = 1 3 4 6 7 9 >> A(2,:)=[] A = 1 2 3 7 8 9 >> A(2,:)=[] A = 1 2 3 7 8 9 delete 2 nd col. delete 2 nd row
29
Matrix, Vector and Array In programming jargon, an n-dimensional field of values is called an array Vector 1-dimensional array Matrix 2-dimensional array Arrays can be multidimensional 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 Page N Page 1 0 0 0 0 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 A(r,c,p) row column page
30
Elementary Math Mathematical Functions Logical Operators
31
Elementary Math Functions abs,sign absolute value and sign functions sin,cos,asin,acos … trigonometric functions exp exponential (base e) log,log10 natural and base-10 logarithm sqrt square root function round round to the nearest integer (whole number)
32
Help on Math Functions Elementary functions ( sin, cos, sqrt, exp, log10 ) help elfun Advanced functions ( bessel, beta, gamma, erf ) help specfun
33
Logical Operations » A = [-2 10 30 -11 Inf 31]; » each_pos = A >= 0 each_pos = 0 1 1 0 1 1 » A = [-2 10 30 -11 Inf 31]; » each_pos = A >= 0 each_pos = 0 1 1 0 1 1 == equal to > greater than < less than >= greater or equal <= less or equal ~ not & and | or == equal to > greater than < less than >= greater or equal <= less or equal ~ not & and | or Note:1 = True 0 = False
34
Graphics in MATLAB
35
2-D Graphics – The plot Command x = 0:pi/100:2*pi; y = sin(x); plot(x,y)
36
…Adding Labels x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x [rad]') ylabel('Sine of x') title('Plot of the Sine Function')
37
…Changing Axis Limits Syntax: axis ([xmin xmax ymin ymax]) x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x [rad]') ylabel('Sine of x') title('Plot of the Sine Function') axis ([0 7 -1.1 1.1])
38
Multiple Graphs x = 0:pi/100:2*pi; y1=sin(x); y2=sin(x+pi/2); plot(x,y1,x,y2) grid on
39
…Adding a Legend x = 0:pi/100:2*pi; y1=sin(x); y2=sin(x+pi/2); plot(x,y1,x,y2) grid on legend('sin(x)','sin(x+\pi/2)') moveable object (mouse!)
40
Multiple Plots x = 0:pi/100:2*pi; y1=sin(x); y2=sin(x+pi/2); subplot(2,1,1) plot(x,y1) subplot(2,1,2) plot(x,y2) Syntax: subplot(rows,cols,index)
41
Subplots Syntax: » subplot(2,2,1); » … » subplot(2,2,2) »... » subplot(2,2,3) »... » subplot(2,2,4) »... » subplot(2,2,1); » … » subplot(2,2,2) »... » subplot(2,2,3) »... » subplot(2,2,4) »... subplot(rows,cols,index)
42
Adding Curves to an Existing Plot Use the hold command to add lines/points to an existing plot. –hold on – retain existing axes, add new curves to current axes. Axes are rescaled when necessary. –hold off – release the current figure window for new plots
43
Multiple Plots x = 0:pi/100:2*pi; y1=sin(x); y2=sin(x+pi/2); subplot(2,1,1) plot(x,y1) subplot(2,1,2) plot(x,y2) hold on plot(x,y1) By default, both lines have the same color.
44
Multiple Plots x = 0:pi/100:2*pi; y1=sin(x); y2=sin(x+pi/2); subplot(2,1,1) plot(x,y1) subplot(2,1,2) plot(x,y2) hold on plot(x,y1,’r’)
45
Plot Qualifiers SymbolColor yyellow mmagenta ccyan rred ggreen bblue wwhite kblack SymbolMarker. o x ++ * s□ d◊ v ^ hhexagram Color SymbolLine Style –solid line :dotted line –.dash-dot line – dashed line Marker Type Line Style To find out more: doc plot and doc linespec
46
3-D Surface Plotting contourf plot3 waterfall contour3 mesh surf
47
Specialized Plotting Routines bar bar3h hist area pie3 rose
48
M-Files An M-file is a text file that consists a group of MATLAB commands MATLAB executes the commands in an M-file exactly as if they were entered in the MATLAB command window So far, we have executed the commands in the command window. A more practical way is to create an M-file.
49
Creating an M-File
50
The M-File Editor Save M File to your working directory
51
Running an M-File Set „current directory“ to your working directory
52
Running an M-File Use right mouse button to assess menu
53
…Result of Running the M-File
54
Bathtub Model Simple model for the filling of a bathtub (with the plug in it): New volume = the old volume + what's been added Or, mathematically:V new = V old + Q * t Inflow per unit time ( t)
55
Numerical Solution of the Bathtub Equation “Initial Condition” Time
56
Repeated Action – “For Loops” for variable = expression commands end Example for t = 1:5000 y(t) = sin (2*pi*t/10); end
57
Bathtub Model 1 What is the modeled water volume after 30 minutes?
58
Bathtub Model 1 n = 30; % no. of timesteps dt = 1.0; % unit time interval [min.] q = 25.0; % inflow rate [liter per min.] % % initialize volume; start with empty bathtub vol(1) = 0.0; % water volume [liter] % % initialize time array time(1) = 0.0; % % loop over time for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; end % % show volume evolution as function of time plot (time, vol) xlabel('Time [min]') ylabel('Water Volume [liter]') Define constants
59
Bathtub Model 1 Define array variables n = 30; % no. of timesteps dt = 1.0; % unit time interval [min.] q = 25.0; % inflow rate [liter per min.] % % initialize volume; start with empty bathtub vol(1) = 0.0; % water volume [liter] % % initialize time array time(1) = 0.0; % % loop over time for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; end % % show volume evolution as function of time plot (time, vol) xlabel('Time [min]') ylabel('Water Volume [liter]')
60
Bathtub Model 1 n = 30; % no. of timesteps dt = 1.0; % unit time interval [min.] q = 25.0; % inflow rate [liter per min.] % % initialize volume; start with empty bathtub vol(1) = 0.0; % water volume [liter] % % initialize time array time(1) = 0.0; % % loop over time for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; end % % show volume evolution as function of time plot (time, vol) xlabel('Time [min]') ylabel('Water Volume [liter]') Use array variable in for-loop
61
Bathtub Model 1 n = 30; % no. of timesteps dt = 1.0; % unit time interval [min.] q = 25.0; % inflow rate [liter per min.] % % initialize volume; start with empty bathtub vol(1) = 0.0; % water volume [liter] % % initialize time array time(1) = 0.0; % % loop over time for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; end % % show volume evolution as function of time plot (time, vol) xlabel('Time [min]') ylabel('Water Volume [liter]') Display result
62
Bathtub Model 1 What is the modeled water volume after 30 minutes? How would the volume change if time goes on? Does this make sense?
63
Modeled Water Volume in Bathtub
64
Bathtub Model 2 Limit the water volume in the bathtub at the maximum possible level If more water flows in, it spills over Control Statement: If (water volume is larger than max. volume) then volume is set to max. volume if (vol > maxvol) vol = maxvol end Condition (logical expression) Action statement carried out if condition is true
65
Bathtub Model 2 n = 30; % no. of timesteps dt = 1.0; % unit time interval [min.] q = 25.0; % inflow rate [liter per min.] maxvol = 500.0; % max. volume that bathtub can hold [liter] % % initialize volume; start with empty bathtub vol(1) = 0.0; % water volume [liter] % % initialize time array time(1) = 0.0; % % loop over time for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; if (vol(i+1) > maxvol) vol(i+1) = maxvol; end; Define max. volume “Spill-over function”
66
Modeled Water Volume in Bathtub with Volume Constraint
67
fopen Open a file for output fprintf Write formatted data to an open file fclose Close open file Saving Variables to a Text File
68
fid = fopen(filename, mode) Opening a Text File File Identifier (a variable) 'r‘ Open file for reading (default) 'w‘ Open file, or create new file, for writing; discard existing contents 'a‘ Open file, or create new file, for writing; append data to the end of the file.
69
fid = fopen(filename, mode) Opening a Text File File Identifier (a variable) 'r‘ Open file for reading (default) 'w‘ Open file, or create new file, for writing; discard existing contents 'a‘ Open file, or create new file, for writing; append data to the end of the file. Example: fid = fopen(‘myfile.txt‘, ‘w‘) File access is in the „Current Directory“
70
fprintf(fid, format, variable) Writing to a Text File directs printing to file w/ this identifier variable(s) to be printed controls alignment, significant digits, field width of the output ( doc fprintf for details)
71
Note: format statement must be enclosed in single quotes (‘) Text output: 'Sample text\n' text output + new line Formatting Examples
72
Note: format statement must be enclosed in single quotes (‘) Text output: 'Sample text\n' text output + new line Decimal notation '%5.1f\n' e.g. 123.4 % convert number into specified format 5 field width incl. decimal point 1 number of decimal places f use decimal notation Formatting Examples
73
Note: format statement must be enclosed in single quotes (‘) Text output: 'Sample text\n ' text output + new line Decimal notation '%5.1f\n' e.g. 123.4 Exponential notation '%5.1E\n' e.g. 123.4E+001 % convert number into specified format 5 field width incl. decimal point 1 number of decimal places E use exponential notation Formatting Examples
74
fclose(fid) Closing a Text File File Identifier (a number)
75
Bathtub Model 3 % open file for output and write header fid = fopen('bathtub.txt','w'); fprintf(fid, '% Bathtub Model\n'); fprintf(fid, '% Column 1: Time [min]\n'); fprintf(fid, '% Column 2: Water Volume [liter]\n'); % fprintf(fid, '%2.0f %5.1f\n', time(1), vol(1)); % loop over time; save output to file for i = 1:n time(i+1) = time(i) + dt; vol(i+1) = vol(i) + q * dt; if (vol(i+1) > maxvol) vol(i+1) = maxvol; end; fprintf(fid, '%2.0f %5.1f\n', time(i+1), vol(i+1)); end;. fclose(fid); Initialize output file Close file Save data to file (within loop)
76
fprintf(fid, '%2.0f %5.1f\n', time(i+1), vol(i+1))
77
fprintf(fid, '%2.0f %4.2E\n', time(i+1), vol(i+1))
79
Additional Material…
80
Matrix Concatenation »a=[1 2;3 4] a = 1 2 3 4 »cat_a=[a 2*a; 3*a 4*a; 5*a 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24 »a=[1 2;3 4] a = 1 2 3 4 »cat_a=[a 2*a; 3*a 4*a; 5*a 6*a] cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24 Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] Note: The resulting matrix must be rectangular 4*a
81
Character Array (String) Created using single quote delimiter (') Each character is a separate matrix element Indexing same as for numeric arrays »str1 = 'Hi there,' str1 = Hi there, »str2 = 'Isn''t MATLAB great?' str2 = Isn't MATLAB great? »str1 = 'Hi there,' str1 = Hi there, »str2 = 'Isn''t MATLAB great?' str2 = Isn't MATLAB great? 1x9 vector str1 = Hithere,
82
»str1 ='Hi there,'; »str2='Everyone!'; »new_str1=[str1, ' ', str2] new_str1 = Hi there, Everyone! »str3 = 'Isn''t MATLAB great?'; »new_str2=[new_str1; str3] new_str2 = Hi there, Everyone! Isn't MATLAB great? »str1 ='Hi there,'; »str2='Everyone!'; »new_str1=[str1, ' ', str2] new_str1 = Hi there, Everyone! »str3 = 'Isn''t MATLAB great?'; »new_str2=[new_str1; str3] new_str2 = Hi there, Everyone! Isn't MATLAB great? 1x19 vector 1x9 vectors String Array Concatenation Using [ ] operator: Each row must be same length Column separator: space / comma (,) Row separator: semicolon (;) For strings of different length: strvcat »new_str3 = strvcat(str1, str3) new_str3 = Hi there, Isn't MATLAB great? »new_str3 = strvcat(str1, str3) new_str3 = Hi there, Isn't MATLAB great? 2x19 matrix (“space padded”) 1x19 vectors
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.