Introduction to MATLAB MATLAB Matrix Manipulations Transportation Infrastructure Systems GS Dr. Antonio Trani Civil and Environmental Engineering Virginia Polytechnic Institute and State University Fall 22 Virginia Polytechnic Institute and State University 1 of 53
Purpose of this Section To illustrate examples of matrix manipulation in MATLAB To learn some of the basic plotting functions in MATLAB Just for the fun of learning something new (the most important reason) Virginia Polytechnic Institute and State University 2 of 53
Basic Matrix Manipulation 434 = 468 b 366 Let A and = A = [4 3 4; 4 6 8; 3 6 6]; b = [35 22 4]'; y = A*b; 35 22 4 Results in column vector y, y = 366 592 477 Virginia Polytechnic Institute and State University 3 of 53
Solution of Linear Equations (I) Suppose we want to solve the set of linear equations: 4x 1 + 3x 2 + 4x 3 = 35 4x 1 + 6x 2 + 8x 3 = 22 3x 1 + 6x 2 + 6x 3 = 4 Then in matrix form we have: Ax = b Virginia Polytechnic Institute and State University 4 of 53
Sol. of Linear Equations (II) where: A 434 = 468 x 366 x 1 x 2 x 3, and = b = 35 22 4 Using MATLAB this can be solved using the operator \ x \ = A b % Solution of linear equations A = [4 3 4; 4 6 8; 3 6 6]; b = [35 22 4]';x = A\b; Virginia Polytechnic Institute and State University 5 of 53
Solution of Linear Equations (III) Yields the following answer for x, x = 12. 15.6667-15. % Another solution of the linear equations A = [4 3 4; 4 6 8; 3 6 6]; b = [35 22 4]'; x = inv(a)*b; This gives the same result taking the inverse of A Virginia Polytechnic Institute and State University 6 of 53
Array vs Scalar MATLAB Operators (I) MATLAB differentiates between array and scalar operators Scalar operators apply to matrices Array operators have a period in front of the operand Array operations in your code should always be stated using a period before the operand. For example: x = :.5:8; y = sin(x^2)*exp(-x); Will not execute correctly because the manipulation of array x requires operands with a period in front (MATLAB nomenclature) Virginia Polytechnic Institute and State University 7 of 53
Array vs. Scalar MATLAB Operators (II) The following script will execute correctly x = :.5:8; y = sin(x.^2).*exp(-x); The following operations are valid and execute correcly A = [3 3 3 ; 2 2 2; 1 1 1]; c = A ^ 2 ; d = A * A ; e = A / 2 ; f = A * 3; Virginia Polytechnic Institute and State University 8 of 53
Array Operators Operation MATLAB Operators Array multiplication.* Array power.^ Left array division.\ Right array division./ Matrix multiplication * Matrix power ^ Matrix division / Left matrix division \ Use these to do basic operations on arrays of any size Virginia Polytechnic Institute and State University 9 of 53
Array Manipulation Tips Always define the size of the arrays to be used in the program (static allocation) Define arrays with zero elements (defines statically array sizes and thus reduces computation time)»d=zeros(1,3) d =»c=ones(1,3) c = 1 1 1 Virginia Polytechnic Institute and State University 1 of 53
Array Manipulation Tips Sample of for-loop without array pre allocation Example: tic; for i=1:1:1; d(i) = sin(i) ; end t=toc; disp(['time to compute array ', num2str(t), ' (seconds)']) Time to compute array 2.4361 (seconds) Virginia Polytechnic Institute and State University 11 of 53
Array Pre allocation Array pre allocation saves time because MATLAB does not have to dynamically change the size of each array as the code executes d=zeros(1,1); % pre allocates a vector with 1k tic; for i=1:1:1; d(i) = sin(i) ; end t=toc; disp(['time to compute array ', num2str(t), ' (seconds)']) Time to compute array.12167 (seconds) Virginia Polytechnic Institute and State University 12 of 53
Vector Operations in MATLAB The following script is equivalent to that shown in the previous page. tic; i=1:1:1; d = sin(i); t=toc; disp(['time to compute array ', num2str(t), ' (seconds)']) Time to compute array.3639 (seconds) Note: MATLAB vector operations are optimized to the point that even compiling this function in C/C++ offers little speed advantage (1-15%). Virginia Polytechnic Institute and State University 13 of 53
Comparison of Results The following table summarizes the array manipulation results Procedure CPU Time a (seconds) Ratio b Standard for-loop 2.4361 1 Array Pre allocation.12167 2 Vectorization.364 669 a.apple PowerPC G3 366 Mhz with OS 8.6 b.higher ratio means faster execution times Virginia Polytechnic Institute and State University 14 of 53
Graphs in MATLAB There are many ways to build plots in MATLAB. Two of the most popular procedures are: 1) Using built-in MATLAB two and three dimensional graphing commands 2) Use the MATLAB Handle Graphics (object-oriented) procedures to modify properties of every object of a graph Handle Graphics is a fairly advanced topic that is also used to create Graphic User Interfaces (GUI) in MATLAB. For now, we turn our attention to the first procedure. Virginia Polytechnic Institute and State University 15 of 53
Plots Using Built-in Functions MATLAB can generally handle most types of 2D and 3D plots without knowing Handle Graphics plot command for 2D plots plot3d for 3D plots Use hold command to superimpose plots interactively or when calling functions Use the zoom function to dynamically resize the screen to new [x,y] limits Use the subplot function to plot several graphs in one screen Virginia Polytechnic Institute and State University 16 of 53
Basic Plots in MATLAB Two-dimensional line plots are easy to implement in MATLAB % Sample line plot x=:.5:5; y=sin(x.^1.8); plot(x,y); xlabel( x ) ylabel( y ) title( A simple plot ) grid Try this out now. % plot command % builds the x label % builds the y label % adds a title % adds hor. and vert. % grids Virginia Polytechnic Institute and State University 17 of 53
Other Types of 2-D Plots bar fplot bar plot simple plot of one variable (x) semilogx and semilogy semilog plots loglog polar plotyy errorbar hist logarithmic plot polar coordinates plot dual dependent variable plot error bar plot histogram plot Virginia Polytechnic Institute and State University 18 of 53
More 2D Plots stem stairs comet contour quiver generates stems at each data point discrete line plot (horizontal lines) simple animation plot plots the contours of a 2D function plots fields of a function Virginia Polytechnic Institute and State University 19 of 53
Sample 2D Plots (semilog plot) x=:.5:5; y=exp(-x.^2); semilogy(x,y); grid 1 1-2 1-4 1-6 1-8 1-1 1-12.5 1 1.5 2 2.5 3 3.5 4 4.5 5 Virginia Polytechnic Institute and State University 2 of 53
Sample 2D Plots (loglog plot) x=:.5:5; y=exp(-x.^2); loglog(x,y); grid 1 1-1 1-3 1-2 1-1 1 Virginia Polytechnic Institute and State University 21 of 53
Sample 2D Plots (bar plot) x = -2.9:.2:2.9; bar(x,exp(-x.*x)); grid 1.9.8.7.6.5.4.3.2.1-3 -2-1 1 2 3 Virginia Polytechnic Institute and State University 22 of 53
Sample 2D Plots (stairs plot) x=:.5:8; stairs(x,sin(x.^2).*exp(-x)); grid.35.3.25.2.15.1.5 -.5 -.1 -.15 1 2 3 4 5 6 7 8 Virginia Polytechnic Institute and State University 23 of 53
Sample 2D Plots (errorbar plot) x=-2:.1:2; y=erf(x); e = rand(size(x))/2; errorbar(x,y,e); grid 1.5 1.5 -.5-1 -1.5-2.5-2 -1.5-1 -.5.5 1 1.5 2 2.5 Virginia Polytechnic Institute and State University 24 of 53
Sample 2D Plots (polar plot) % Polar plot t=:.1:2*pi; polar(t,sin(2*t).*cos(2*t)); 12 9.5.375 6 15.25 3.125 18 21 33 24 27 3 Virginia Polytechnic Institute and State University 25 of 53
Sample 2D Plots (stem plot) x = :.1:4; y = sin(x.^2).*exp(-x); stem(x,y); grid.35.3.25.2.15.1.5 -.5 -.1 -.15.5 1 1.5 2 2.5 3 3.5 4 Virginia Polytechnic Institute and State University 26 of 53
Sample 2D Plots (Histogram) x=randn(1,1); hist(x); grid 3 25 2 15 1 5-4 -3-2 -1 1 2 3 4 Virginia Polytechnic Institute and State University 27 of 53
Sample 2D Plots (plotyy) x=-2:.1:2; y1=erf(x); y2=erf(1.35.*x); plotyy(x,y,x,y2);grid.5 1 -.5-2 -1.5-1 -.5.5 1 1.5 2-1 Virginia Polytechnic Institute and State University 28 of 53
Sample 2D Plot (pie plot) In this example we demonstrate the use of the gtext function to write a string at the location of the mouse acft = char('a31','a33','md11','dc-1', 'L111',... 'B747','B767','B777'); numbers=[12 15 24 35 16 12 456 156]; pie(numbers) for i=1:8 % array of strings gtext(acft(i,:)); % get text from char variable end title('aircraft Performing N. Atlantic Crossings') Virginia Polytechnic Institute and State University 29 of 53
Resulting Pie Plot Aircraft Performing N. Atlantic Crossings A33 A31 4% 2% DC-1 MD11 L111 3% 2%1% B747 19% B777 14% 55% B767 Virginia Polytechnic Institute and State University 3 of 53
Quiver Plot The quiver plot is good to represent vector fields. In the example below a quiver plot shows the gradient of a function called peaks t=-3:.1:3; [x,y]=meshgrid(t,t); z= 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2)... - 1*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2)... - 1/3*exp(-(x+1).^2 - y.^2); [dx,dy]=gradient(z,.2,.2); quiver(x,y,dx,dy,3) Note: peaks is a built-in MATLAB function Virginia Polytechnic Institute and State University 31 of 53
Quiver Plot of Peaks Function 3 2 1-1 -2-3 -4-4 -3-2 -1 1 2 3 4 Virginia Polytechnic Institute and State University 32 of 53
3D Representation of the Peaks Function Peaks 8 6 4 2-2 -4-6 3 2 1 y -1-2 -3-3 -2-1 x 1 2 3 Virginia Polytechnic Institute and State University 33 of 53
2D Plots (Contour Plot) The following script generates a contour plot of the peaks function t=-3:.1:3; [x,y]=meshgrid(t,t); z= 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2)... - 1*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2)... - 1/3*exp(-(x+1).^2 - y.^2); colormap(lines) contour(x,y,z,15) % 15 contours are generated grid Virginia Polytechnic Institute and State University 34 of 53
Resulting Contour Plot of the Peaks Function 3 2 1-1 -2-3 -3-2 -1 1 2 3 Virginia Polytechnic Institute and State University 35 of 53
Sample 2D Plots (comet plot) Useful to animate a trajectory Try the following script % illustration of comet plot x = :.5:8; y = sin(x.^2).*exp(-x); comet(x,y) Virginia Polytechnic Institute and State University 36 of 53
Handling Complex 2-D Plots Tampa Bay Atlantic Ocean Aircraft Tracks Miami Intl. Airport Gulf of México -84-83 -82-81 -8-79 -78-77 Longitude (deg.) Virginia Polytechnic Institute and State University 37 of 53
Zooming Into Previous Plot Arrivals Departures Miami Intl. Airport -81-8.8-8.6-8.4-8.2-8 -79.8 Longitude (deg.) Virginia Polytechnic Institute and State University 38 of 53
Sample Use of Subplot Function Used the subplot function to display various graphs on the same screen % Demo of subplot function x = :.1:4; y = sin(x.^2).*exp(-x); z=gradient(y,.1) % takes the gradient of y every %.1 units subplot(2,1,1) plot(x,y); grid subplot(2,1,2) plot(x,z); grid % generates the top plot % generates the lower plot Virginia Polytechnic Institute and State University 39 of 53
Resulting Subplot.6.4.2 -.2.5 1 1.5 2 2.5 3 3.5 4.5 -.5-1.5 1 1.5 2 2.5 3 3.5 4 Virginia Polytechnic Institute and State University 4 of 53
Sample Plot Commands Standard 2D plot using the subplot function Latitude (deg) 4 35 3 25-13 -12-11 -1-9 -8-7 -6 Longitude (deg) 12 Occupancy of Sector 15 : OCF 1 Traffic (acft) 8 6 4 2 11 112 114 116 118 12 122 124 126 128 13 Reference Time (min) Virginia Polytechnic Institute and State University 41 of 53
Zoom Command The zoom command is used to examine a smaller area 31 Latitude (deg) 3 29 28 27-9 -88-86 -84-82 -8-78 -76 Longitude (deg) 12 Occupancy of Sector 15 : OCF 1 Traffic (acft) 8 6 4 2 11 112 114 116 118 12 122 124 126 128 13 Reference Time (min) Virginia Polytechnic Institute and State University 42 of 53
3-D Graphing in MATLAB A 3-D plot could help you visualize complex information 3D animations can be generated from static 3D plots 3D controls fall into the following categories: - viewing control (azimuth and elevation) - color control (color maps) - lighting control (specular, diffuse, material, etc.) - axis control - camera control - graph annotation control - printing control Virginia Polytechnic Institute and State University 43 of 53
Viewing Control 3D plots have two viewing angles than can be controlled with the command view - azimuth - elevation Example use: view(azimuth, elevation) Default viewing controls are: -37.5 degrees in azimuth and 3 degrees in elevation Try the traffic file changing a few times the viewing angle Virginia Polytechnic Institute and State University 44 of 53
Rotating Interactively a 3D Plot Use the rotate3d command to view interactively the 3D plots (good for quantitative data analysis) The zoom command does not work in 3D >> plot3d(x,y,z) >> rotate3d >> Try rotating the traffic characteristics file using rotate3d Virginia Polytechnic Institute and State University 45 of 53
Sample 3D Plot (plot3 function) plot3(density,speed,volume,'*') 35 3 Volume (veh/hr) 25 2 15 1 TextEnd 5 8 6 15 4 1 2 5 Density (veh/la-km) Speed (km/hr) Virginia Polytechnic Institute and State University 46 of 53
Rotate Command The rotate3d command is useful to visualize 3D data interactively 35 3 25 Volume (veh/hr) 2 15 1 5 8 TextEnd 6 4 Density (veh/la-km) 2 2 4 6 Speed (km/hr) 8 1 12 14 Virginia Polytechnic Institute and State University 47 of 53
Sample 3D Graphics (mesh) % Mesh Plot of Peaks z=peaks(5); mesh(z); 1 5-5 -1 5 4 3 2 1 1 2 3 4 5 Virginia Polytechnic Institute and State University 48 of 53
z=peaks(25); surf(z); colormap(jet); ; Sample 3D Graphics (surf) 8 6 4 2-2 -4-6 -8 25 2 15 1 5 5 1 15 2 25 Virginia Polytechnic Institute and State University 49 of 53
Sample 3D Graphics (surfl) z=peaks(25); surfl(z); shading interp; colormap(jet);; 8 6 4 2-2 -4-6 -8 25 2 15 1 5 5 1 15 2 25 Virginia Polytechnic Institute and State University 5 of 53
Sample 3D Graphics (slice) Slice 3D plots visualize the internal structure of set of numbers as gradients [x,y,z] = meshgrid(-2:.2:2,-2:.2:2,-2:.2:2); v = x.* exp(-x.^2 - y.^2 - z.^2); slice(v,[5 15 21],21,[1 1]) axis([ 21 21 21]); colormap(jet) Virginia Polytechnic Institute and State University 51 of 53
Slice Plot of Pseudo-Gaussian Function 2 15 1 5 2 15 1 5 5 1 15 2 Virginia Polytechnic Institute and State University 52 of 53
Sample 3D Graphics (stem3) stem3 - plots stems in three dimensions as shown below 35 3 Volume (veh/hr) 25 2 15 1 5 TextEnd 8 6 15 4 1 2 5 Density (veh/la-km) Speed (km/hr) Virginia Polytechnic Institute and State University 53 of 53