Matlab Graphics Cheng-An Yang September 22, 2013
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Outline 1 2D Plots 2 The Graphical User Interface 3 Advanced Topics 4 Animation 5 3D Plots 6 More Plots 7 Extra 2 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 1 2D Plots 3 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Figure: create Syntax • To create an empty figure, call figure(); • You can also number your figure like figure(42); 4 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Figure: close Syntax • Close a specific figure close(42); • Close all figures close all; 5 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plot Syntax • To create a line plot of vector y versus vector t, use plot(t,y); • What happen if you don’t provide the x-axis data? Try plot(y); 6 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Multiple Lines Syntax • You can input more vector pairs like plot(t1,y1,t2,y2); 7 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Multiple Lines Visualize three elementary functions on 0 ≤ t ≤ 2π: y1 = sin(t) y2 = cos(t) y3 = e−t Plot them on the same figure. 8 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Adding Labels Syntax • Adding labels on axis xlabel(’x label’); ylabel(’y label’); • Adding title title(’title for the figure’); • Adding legends legend(’first’,’second’,...); 9 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Grid Syntax • Turn on/off the grid lines grid on; grid off; 10 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Changing the Axes Limits Syntax • Set the limits of each axis axis([xmin xmax ymin ymax]); • If you want to adjust only x-axis or y-axis, xlim([xmin xmax]); ylim([ymin ymax]); 11 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Customize Plots • Using the string specifier to change the line style. • The string specifiers contains • Line style: {’-’,’--’,’:’,’-.’,’none’} • Marker symbol: {’+’,’o’,’*’,’.’,’x’} and more. • Color: {’r’,’g’,’b’,’w’,’k’}. • For example, plot(t,x,’--or’); plot(t,x,’r’,t,y,’-.xk’); 12 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The Envelop Please duplicate the figure shown below: 0 5 10 −1 −0.5 0 0.5 1 The blue line is x = t2 cos(5t)e−t . (1) The envelope of x(t) is y = ±t2 e−t . (2) 13 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plot Matrix Data Syntax • By default plot(Y) will plot each column of Y. • When specifying the x vector, plot(x,Y); will try to match the dimension of x and Y. 14 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Plot Matrix Data Let Y = [ y1; y2; y3 ]; • What is the dimension of Y? • Try plot(t,Y) and plot(Y). Can you anticipate the outputs? 15 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plot Complex Data Syntax • To plot complex array x, use plot(x); • It is equivalent to plot(real(x),imag(x)); 16 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The Eigenvalues of Random Matrices Gaussian Random Matrix A Gaussian Random Matrix H is a matrix with standard normal components hij d = N (0, 1). h11 h22 h12 h21 TX1 TX2 RX1 RX2 • Arises in many applications. • Wireless communication. • Channel gain hij is random. 17 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The Eigenvalues of Random Matrices Visualizing the distribution of the eigenvalues of random matrices. • Generate H = randn(n,n). • [V,D] = eig(H). • Plot its eigenvalues as dots on the complex plane. • Increase n form 10 to 1, 000. Can you tell what’s the pattern of the eigenvalues? 18 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plotting Multiple Lines On the Same Axes • If you call plot twice, the first plot will be erased. • To retain current graph when adding new graph, tell Matlab to hold on; • If you want different lines to have different color, use hold all; • The default is hold off; 19 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Exponent and Convexity 0 0.2 0.4 0.6 0.8 1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 x x n 0.1 0.5 1 2 10 • The function xα is convex when α ≥ 1. • When 0 < α < 1 is it concave. • Use a for loop and hold to verify this. • α = {0.1, 0.5, 1, 2, 10}. 20 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 2 The Graphical User Interface 21 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra The GUI 22 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Saving and Loading Some tips: • Save your file in vector formats, such as .eps and .pdf. • Use ‘copy figure’ between applications. • Keep a .fig copy so you can edit it later. 23 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Customization Using GUI • Click the ‘Edit Plot’ icon. • Double click on the figure to enter the editing mode. • Select an object, and the property editor will appear. 24 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Frequency Response • The transfer function of a second order system has the form H(s) = ω2 n s2 + 2ζωns + ω2 n , where ζ is the damping ratio and ωn is the natural frequency. • The frequency response of a system is characterized by • The magnitude |H(ω)| • The phase ∠H(ω) 25 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Frequency Response 10 −1 10 0 10 1 −100 −50 0 50 Frequency (rad) Magnitude(dB) 10 −1 10 0 10 1 −π −π/2 0 Frequency (rad) Phase(rad) • Let ωn = 1, ζ = 0.2. • Frequencies from 10−1 to 10 (rad). • The unit imaginary number in Matlab is 1j and 1i. • Note the magnitude response is defined as 20 log(|H(ω)|). • You may want to use angle and logspace. 26 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 1 The Bessel functions Jα(x) of the first kind and order α is the solution to the Bessel’s Equation x2 d2y dx2 + x dy dx + (x2 − α2 )y = 0. • Separable solution to many important PDE in cylindrical coordinate. • Useful in physics, signal processing and statistics. 27 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 1 Bessel function has the following representation Bessel Functions of the First Kind Jα(x) = ∞ m=0 (−1)m m! Γ(m + α + 1) 1 2 x 2m+α . Matlab has built-in function for Jα(x) Syntax J = besselj(alpha, x); 28 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 1 Visualizing Jα(x) with different α. Please create a figure like this: 0 1 2 3 10 15 0.0 1.0 x Jα(x) α = 0 α = 1 α = 2 α = 3 α = 10 • α = {0, 1, 2, 3, 10}. • 0 ≤ x ≤ 15. Note that some tick labels are omitted. • Use alpha for α. • Insert a text box near the maximum amplitude of each function. 29 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exploring Data • Change view point, zoom in/out, pan. • Create multiple datatips. • Select/Brush Data tool. 30 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Select And Linking Data • Open the Variable Editor. • Click the ‘Link Plot’ icon. • Click the ‘Select/Brush Data’ icon. • Select the data of interest. 31 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Wave Editing • Load the chirp.mat file. • Type sound(y,Fs) to play it. • Use data selection tool to select and ‘mute’ the chirps. • Play the modified recording. 32 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 3 Advanced Topics 33 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Why Learning Commands? • Almost everything can be adjusted using GUI, why learning commands? • If you only need to edit a figure or two, use GUI. • If you have a dozen of figures, let computers do the work. • To create an animation, you have to know the commands. • Programmer’s pride. 34 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Hierarchy of The Graphic Objects A Matlab plot is composed of (at least) three objects: (a) Figure window. (b) Axis object. (c) Line series object. 35 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Get a Handle on Objects • Each object has a unique identifier, called the handle. • You can ask Matlab to get and set the properties of the object with its handle. • To get the handle of the current figure, type h_fig = gcf; • To get the handle of the current axis, type h_ax = gca; • To get the handle of the line series, use h = plot(t,x); 36 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Get and Set Property • Get the value of the property: value = get(h,’PropertyName’); • Set using property-value pair: set(h,’PropertyName’,value); 37 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Batch Process • The command saveas(h_fig, ’file_name’, ’fig’); will save the figure h fig as file name.fig. • You can replace the third argument by other format. Type help saveas for more information. • Write a script that does the following: • For each frequency ω = {1, 2, . . . , 10}, plot sin(ωt) on 0 ≤ t ≤ 2π in 10 separate figures. • Save and name them as freq1.fig, freq2.fig,... freq10.fig files. • Hint: the command sprintf(’freq%d.fig’,I) will generate the desired file name, where I is an integer. 38 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Subplot Syntax subplot(m,n,1); plot(t,x); Will create a m-by-n subplot and place the plot of x versus t at location 1. 39 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Sine Wave Matrix Create 25 subplots of sine wave with increasing frequency. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 40 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 4 Animation 41 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Making Animated Sequences • The simplest way: continually erase and redraw your figure. • Key ingredients: • Loop. • Update data. • Erase and redraw. • Pause. Example for I = 1:N % Loop. x = sin(t-I); % Update data. plot(t,x); % Erase and Redraw. pause(0.1); % Pause for 0.1 sec. end 42 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Example: Vibrating String Standing Wave As oppose to a travelling wave, a standing wave oscillates in place without propagating. Mathematically it is described by y = A cos(ωt) sin(kx), where ω is the angular frequency and k is the wave number. • Let ω = 5, k = 1.5, A = 2. • Let 0 ≤ x ≤ 2π. • Make an animation of such a standing wave. 43 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 2 Standing Wave A standing wave y can be seen as the result of interference between two waves y1 and y2 travelling in opposite directions. Mathematically, y1 = A sin(kx − ωt) y2 = A sin(kx + ωt) and y = A sin(kx−ωt)+A sin(kx+ωt). • A: amplitude. • k: wave number. • ω: angular velocity. 44 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 2 Create an animation of a standing wave. 0 2 4 6 8 10 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 • A = 1, k = 1, ω = 3. • Red wave: from left to right. • Blue wave: from right to left. • Black wave: the resulting standing wave. • Try update rate dt = 0.05. • Add a reference line x = 0. • Bonus problem: labelling the nodes. (the red circles) 45 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 5 3D Plots 46 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra 3D Line Plot For parametric data (x(t), y(t), z(t)), we can use the 3D version of the plot function. Syntax • Plot lines in 3D plot3(x,y,z); 47 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Brownian Motion −50 0 50 −20 0 20 −20 0 20 The position vector xn of a Brownian particle at time n is given by xn = xn−1 + v, where v is a standard normal random vector. • Simulate the path of two Brownian particles starting at the origin. • Take N = 500 steps. 48 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Representing Matrix Data −10 0 10 −10 0 10 −0.5 0 0.5 1 • Line series are represented by vectors. • Data with 2D indices are represented by matrices. • Think of the values of matrix Z as “height”. • The indices of x-axis and y-axis are stored in matrix X and Y. 49 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Mesh Grid and Surface Plot To visualize a function f (x, y) on (x, y) ∈ [a, b] × [c, d], • First we need to create a rectangular grid. • Matlab provides a useful function to create such a grid: [X,Y] = meshgrid(x,y); where x and y are the sampling points on both axis. • Then we can use surf(X,Y,f(X,Y)); to produce a surface plot. 50 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The 3D Sinc Function 3D Sinc Function sinc(r) := sin(r) r , where r2 = x2 + y2. • Visualize the 3D sinc function on (x, y) ∈ [−8, 8] × [−8, 8]. • One way to avoid the divided-by-zero error is to use sin(r)./(r+esp) instead of sin(r)./r. • esp is the smallest representable floating point number in Matlab. 51 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Contour Plot • Surface plot is fancy but not suitable for putting in your paper! • Contour plot might be more appropriate. Syntax • The basic syntax is contour(Z); • You can specify the number of contour level contour(Z, n_level); 52 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Scalar Field Let f (x, y) = x2 − 3 sin(xy). Use contour plot to visualize f (x, y) on [−2, 2] × [−2, 2]. 53 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Vector Field A 2D vector field is a vector-valued function z(x, y) = zx (x) zy (y) . Matlab provides a function to visualize vector files. Syntax • Plot the vector field Zx and Zy as a function of X and Y quiver(X,Y,Zx,Zy); 54 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Scalar Field and its Gradient • The gradient of a scalar field f (x, y) is defined as f = ∂ ∂x f ∂ ∂y f . • Numerically, we can approximate the partial derivative by ∂ ∂x f (x, y) ≈ f (x + h, y) − f (x, y) h for some small number h. • In Matlab, we can use gradient(F) to find the gradient of the scalar field F. See help for more detail. 55 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Scalar Field and its Gradient −2 −1 0 1 −2 −1 0 1 • Find the gradient of the scalar field f (x, y) = x2 − 3 sin(xy). • Plot f (x, y) using contour(). • Plot its gradient using gradient() in the same figure. 56 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 6 More Plots 57 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Histogram Histogram is useful to visualize the distribution of univariate data. Syntax • Create a histogram of data vector x hist(x); • To specify number of bins, use hist(x,m); 58 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Random Number Generators • Two important random number generators in Matlab: • Uniform between 0 and 1: rand(). • Standard normal: randn(). • Exercise: • Generate N random samples from rand(). • Use hist to visualize the distribution. • Experiment with different N and different number of bins. • How many samples are required to produce a good approximation of it distribution? • Repeat for randn(). 59 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Area, Bar and Pie Chart Syntax • Stacks each data series and fill the underlying area with different colors area(X,Y); • Create a bar chart bar(Y); Each column of Y will have the same color and rows are grouped together. • Pie chart pie(Y); 60 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Operating System War! • Go to http://www.netmarketshare.com/ and download the operating system share trend data (Excel file). • Import it into workspace. • Create the following plots: • Line plot. • Area chart. • Bar chart. • Pie chart on April, 2012. 61 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Scatter Plot Scatter plot is used to visualize the distribution of two dimensional data. Syntax • To generate the scatter plot for the data vector X and Y scatter(X,Y) 62 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Basic Regression • Suppose we are given a data set x and y. • It is assumed that y = ax + b + noise. • Find the best linear fit ˆy = ˆax + ˆb. 0 0.5 1 2 3 4 5 6 x y ˆy = 2.0x + 3.0 63 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 7 Extra 64 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Solving Differential Equations • Differential equation involves derivatives of a function in its independent variables. • Almost everything is described by some differential equation. • Mostafa will talk about solving differential equations using powerful tools provided by Matlab. • We can create a poor man’s differential equation solver. • The idea of Finite Difference Method (FDM): ∂u ∂t ≈ u(t + h) − u(t) h for small h. 65 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra The Finite Difference Method • Consider the wave equation utt = c2 ∆u − but, where the Laplacian operator ∆ is defined as ∆u = uxx + uyy . • Use finite difference to approximate derivatives: ut ≈ u(t + ∆t) − u(t) ∆t utt ≈ u(t + ∆t) − 2u(t) + u(t − ∆t) ∆t2 . Similarly for uxx and uyy . 66 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra The Finite Difference Method • In Matlab, we can use the discrete Laplacian function del2 to approximate ∆u ≈ 4 h2 del2(u), where h is the spacing in the spatial grid. • Substitute the derivatives by their finite difference approximation, we get (verify this!) u(t+∆t) ≈ 2u(t)−u(t−∆t)+h2 ∆u(t)−b∆t(u(t)−u(t−∆t)). (3) • Provide the initial data of u and ut at t = 0 and the boundary condition, we can approximate the solution of the wave equation by recursively solving (3). 67 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Demo: 2D Wave Equation −4 −2 0 2 4 −4 −2 0 2 4 0 2 4 6 8 10 Figure: The simulated solution to the wave equation. 68 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Linear Congruential Generator (LCG) • LCG is a popular (and old) Pseudo-Random Numbers Generator. • Simple and efficient to compute. • Poor choice of parameters lead to bad performance. LCG xn+1 ≡ (axn + b) (mod m), (4) • m > 0: the modulus • a > 0: the multiplier • b ≥ 0: the increment • x0: the seed 69 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Histogram 0 10 20 30 0 5 10 15 • Try different parameters and use hist to evaluate its performance. • If you can’t figure out what combination of parameters would work, try • a = 3 • b = 0 • m = 31 • x0 = 1 70 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Polar Plot • Sometimes it is easier to express coordinate in the polar form. • Let (x, y) be the coordinates in the Cartesian coordinate system, its corresponding polar coordinates is given by r = x2 + y2 (5) θ = tan−1 (y/x). (6) Syntax • Plot r versus theta in the polar coordinate polar(theta,r); 71 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Butterfly Curve The butterfly fly curve, discovered by Temple H. Fay, is generated by the equations r = esin θ − 2 cos(4θ) + sin5 2θ − π 24 . (7) 2 4 6 30 210 60 240 90 270 120 300 150 330 180 0 72 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Demo: Lorenz Attractor Lorenz system is a simplified model for atmospheric convection, it is modeled by the ordinary differential equations dx dt = σ(y − x), (8) dy dt = x(ρ − z) − y, (9) dz dt = xy − βz, (10) where x, y and z are the coordinate of the state, t represents time, ρ, σ and β are parameters. 73 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra 3D Line Plot Example Lorenz Attractor −20 0 20 −50 0 50 0 20 40 60 x y z 74 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Visualizing Gibbs’ Phenomena 75 / 76
2D Plots The Graphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Complex Data as 2D Representation Plot the Hypocycloid. 76 / 76

Matlab Graphics Tutorial

  • 1.
  • 2.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Outline 1 2D Plots 2 The Graphical User Interface 3 Advanced Topics 4 Animation 5 3D Plots 6 More Plots 7 Extra 2 / 76
  • 3.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 1 2D Plots 3 / 76
  • 4.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Figure: create Syntax • To create an empty figure, call figure(); • You can also number your figure like figure(42); 4 / 76
  • 5.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Figure: close Syntax • Close a specific figure close(42); • Close all figures close all; 5 / 76
  • 6.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plot Syntax • To create a line plot of vector y versus vector t, use plot(t,y); • What happen if you don’t provide the x-axis data? Try plot(y); 6 / 76
  • 7.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Multiple Lines Syntax • You can input more vector pairs like plot(t1,y1,t2,y2); 7 / 76
  • 8.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Multiple Lines Visualize three elementary functions on 0 ≤ t ≤ 2π: y1 = sin(t) y2 = cos(t) y3 = e−t Plot them on the same figure. 8 / 76
  • 9.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Adding Labels Syntax • Adding labels on axis xlabel(’x label’); ylabel(’y label’); • Adding title title(’title for the figure’); • Adding legends legend(’first’,’second’,...); 9 / 76
  • 10.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Grid Syntax • Turn on/off the grid lines grid on; grid off; 10 / 76
  • 11.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Changing the Axes Limits Syntax • Set the limits of each axis axis([xmin xmax ymin ymax]); • If you want to adjust only x-axis or y-axis, xlim([xmin xmax]); ylim([ymin ymax]); 11 / 76
  • 12.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Customize Plots • Using the string specifier to change the line style. • The string specifiers contains • Line style: {’-’,’--’,’:’,’-.’,’none’} • Marker symbol: {’+’,’o’,’*’,’.’,’x’} and more. • Color: {’r’,’g’,’b’,’w’,’k’}. • For example, plot(t,x,’--or’); plot(t,x,’r’,t,y,’-.xk’); 12 / 76
  • 13.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The Envelop Please duplicate the figure shown below: 0 5 10 −1 −0.5 0 0.5 1 The blue line is x = t2 cos(5t)e−t . (1) The envelope of x(t) is y = ±t2 e−t . (2) 13 / 76
  • 14.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plot Matrix Data Syntax • By default plot(Y) will plot each column of Y. • When specifying the x vector, plot(x,Y); will try to match the dimension of x and Y. 14 / 76
  • 15.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Plot Matrix Data Let Y = [ y1; y2; y3 ]; • What is the dimension of Y? • Try plot(t,Y) and plot(Y). Can you anticipate the outputs? 15 / 76
  • 16.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plot Complex Data Syntax • To plot complex array x, use plot(x); • It is equivalent to plot(real(x),imag(x)); 16 / 76
  • 17.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The Eigenvalues of Random Matrices Gaussian Random Matrix A Gaussian Random Matrix H is a matrix with standard normal components hij d = N (0, 1). h11 h22 h12 h21 TX1 TX2 RX1 RX2 • Arises in many applications. • Wireless communication. • Channel gain hij is random. 17 / 76
  • 18.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The Eigenvalues of Random Matrices Visualizing the distribution of the eigenvalues of random matrices. • Generate H = randn(n,n). • [V,D] = eig(H). • Plot its eigenvalues as dots on the complex plane. • Increase n form 10 to 1, 000. Can you tell what’s the pattern of the eigenvalues? 18 / 76
  • 19.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Plotting Multiple Lines On the Same Axes • If you call plot twice, the first plot will be erased. • To retain current graph when adding new graph, tell Matlab to hold on; • If you want different lines to have different color, use hold all; • The default is hold off; 19 / 76
  • 20.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Exponent and Convexity 0 0.2 0.4 0.6 0.8 1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 x x n 0.1 0.5 1 2 10 • The function xα is convex when α ≥ 1. • When 0 < α < 1 is it concave. • Use a for loop and hold to verify this. • α = {0.1, 0.5, 1, 2, 10}. 20 / 76
  • 21.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 2 The Graphical User Interface 21 / 76
  • 22.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra The GUI 22 / 76
  • 23.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Saving and Loading Some tips: • Save your file in vector formats, such as .eps and .pdf. • Use ‘copy figure’ between applications. • Keep a .fig copy so you can edit it later. 23 / 76
  • 24.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Customization Using GUI • Click the ‘Edit Plot’ icon. • Double click on the figure to enter the editing mode. • Select an object, and the property editor will appear. 24 / 76
  • 25.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Frequency Response • The transfer function of a second order system has the form H(s) = ω2 n s2 + 2ζωns + ω2 n , where ζ is the damping ratio and ωn is the natural frequency. • The frequency response of a system is characterized by • The magnitude |H(ω)| • The phase ∠H(ω) 25 / 76
  • 26.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Frequency Response 10 −1 10 0 10 1 −100 −50 0 50 Frequency (rad) Magnitude(dB) 10 −1 10 0 10 1 −π −π/2 0 Frequency (rad) Phase(rad) • Let ωn = 1, ζ = 0.2. • Frequencies from 10−1 to 10 (rad). • The unit imaginary number in Matlab is 1j and 1i. • Note the magnitude response is defined as 20 log(|H(ω)|). • You may want to use angle and logspace. 26 / 76
  • 27.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 1 The Bessel functions Jα(x) of the first kind and order α is the solution to the Bessel’s Equation x2 d2y dx2 + x dy dx + (x2 − α2 )y = 0. • Separable solution to many important PDE in cylindrical coordinate. • Useful in physics, signal processing and statistics. 27 / 76
  • 28.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 1 Bessel function has the following representation Bessel Functions of the First Kind Jα(x) = ∞ m=0 (−1)m m! Γ(m + α + 1) 1 2 x 2m+α . Matlab has built-in function for Jα(x) Syntax J = besselj(alpha, x); 28 / 76
  • 29.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 1 Visualizing Jα(x) with different α. Please create a figure like this: 0 1 2 3 10 15 0.0 1.0 x Jα(x) α = 0 α = 1 α = 2 α = 3 α = 10 • α = {0, 1, 2, 3, 10}. • 0 ≤ x ≤ 15. Note that some tick labels are omitted. • Use alpha for α. • Insert a text box near the maximum amplitude of each function. 29 / 76
  • 30.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exploring Data • Change view point, zoom in/out, pan. • Create multiple datatips. • Select/Brush Data tool. 30 / 76
  • 31.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Select And Linking Data • Open the Variable Editor. • Click the ‘Link Plot’ icon. • Click the ‘Select/Brush Data’ icon. • Select the data of interest. 31 / 76
  • 32.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Wave Editing • Load the chirp.mat file. • Type sound(y,Fs) to play it. • Use data selection tool to select and ‘mute’ the chirps. • Play the modified recording. 32 / 76
  • 33.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 3 Advanced Topics 33 / 76
  • 34.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Why Learning Commands? • Almost everything can be adjusted using GUI, why learning commands? • If you only need to edit a figure or two, use GUI. • If you have a dozen of figures, let computers do the work. • To create an animation, you have to know the commands. • Programmer’s pride. 34 / 76
  • 35.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Hierarchy of The Graphic Objects A Matlab plot is composed of (at least) three objects: (a) Figure window. (b) Axis object. (c) Line series object. 35 / 76
  • 36.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Get a Handle on Objects • Each object has a unique identifier, called the handle. • You can ask Matlab to get and set the properties of the object with its handle. • To get the handle of the current figure, type h_fig = gcf; • To get the handle of the current axis, type h_ax = gca; • To get the handle of the line series, use h = plot(t,x); 36 / 76
  • 37.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Get and Set Property • Get the value of the property: value = get(h,’PropertyName’); • Set using property-value pair: set(h,’PropertyName’,value); 37 / 76
  • 38.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Batch Process • The command saveas(h_fig, ’file_name’, ’fig’); will save the figure h fig as file name.fig. • You can replace the third argument by other format. Type help saveas for more information. • Write a script that does the following: • For each frequency ω = {1, 2, . . . , 10}, plot sin(ωt) on 0 ≤ t ≤ 2π in 10 separate figures. • Save and name them as freq1.fig, freq2.fig,... freq10.fig files. • Hint: the command sprintf(’freq%d.fig’,I) will generate the desired file name, where I is an integer. 38 / 76
  • 39.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Subplot Syntax subplot(m,n,1); plot(t,x); Will create a m-by-n subplot and place the plot of x versus t at location 1. 39 / 76
  • 40.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Sine Wave Matrix Create 25 subplots of sine wave with increasing frequency. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 40 / 76
  • 41.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 4 Animation 41 / 76
  • 42.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Making Animated Sequences • The simplest way: continually erase and redraw your figure. • Key ingredients: • Loop. • Update data. • Erase and redraw. • Pause. Example for I = 1:N % Loop. x = sin(t-I); % Update data. plot(t,x); % Erase and Redraw. pause(0.1); % Pause for 0.1 sec. end 42 / 76
  • 43.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Example: Vibrating String Standing Wave As oppose to a travelling wave, a standing wave oscillates in place without propagating. Mathematically it is described by y = A cos(ωt) sin(kx), where ω is the angular frequency and k is the wave number. • Let ω = 5, k = 1.5, A = 2. • Let 0 ≤ x ≤ 2π. • Make an animation of such a standing wave. 43 / 76
  • 44.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 2 Standing Wave A standing wave y can be seen as the result of interference between two waves y1 and y2 travelling in opposite directions. Mathematically, y1 = A sin(kx − ωt) y2 = A sin(kx + ωt) and y = A sin(kx−ωt)+A sin(kx+ωt). • A: amplitude. • k: wave number. • ω: angular velocity. 44 / 76
  • 45.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Graded Task 2 Create an animation of a standing wave. 0 2 4 6 8 10 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2 • A = 1, k = 1, ω = 3. • Red wave: from left to right. • Blue wave: from right to left. • Black wave: the resulting standing wave. • Try update rate dt = 0.05. • Add a reference line x = 0. • Bonus problem: labelling the nodes. (the red circles) 45 / 76
  • 46.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 5 3D Plots 46 / 76
  • 47.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra 3D Line Plot For parametric data (x(t), y(t), z(t)), we can use the 3D version of the plot function. Syntax • Plot lines in 3D plot3(x,y,z); 47 / 76
  • 48.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Brownian Motion −50 0 50 −20 0 20 −20 0 20 The position vector xn of a Brownian particle at time n is given by xn = xn−1 + v, where v is a standard normal random vector. • Simulate the path of two Brownian particles starting at the origin. • Take N = 500 steps. 48 / 76
  • 49.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Representing Matrix Data −10 0 10 −10 0 10 −0.5 0 0.5 1 • Line series are represented by vectors. • Data with 2D indices are represented by matrices. • Think of the values of matrix Z as “height”. • The indices of x-axis and y-axis are stored in matrix X and Y. 49 / 76
  • 50.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Mesh Grid and Surface Plot To visualize a function f (x, y) on (x, y) ∈ [a, b] × [c, d], • First we need to create a rectangular grid. • Matlab provides a useful function to create such a grid: [X,Y] = meshgrid(x,y); where x and y are the sampling points on both axis. • Then we can use surf(X,Y,f(X,Y)); to produce a surface plot. 50 / 76
  • 51.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: The 3D Sinc Function 3D Sinc Function sinc(r) := sin(r) r , where r2 = x2 + y2. • Visualize the 3D sinc function on (x, y) ∈ [−8, 8] × [−8, 8]. • One way to avoid the divided-by-zero error is to use sin(r)./(r+esp) instead of sin(r)./r. • esp is the smallest representable floating point number in Matlab. 51 / 76
  • 52.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Contour Plot • Surface plot is fancy but not suitable for putting in your paper! • Contour plot might be more appropriate. Syntax • The basic syntax is contour(Z); • You can specify the number of contour level contour(Z, n_level); 52 / 76
  • 53.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Scalar Field Let f (x, y) = x2 − 3 sin(xy). Use contour plot to visualize f (x, y) on [−2, 2] × [−2, 2]. 53 / 76
  • 54.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Vector Field A 2D vector field is a vector-valued function z(x, y) = zx (x) zy (y) . Matlab provides a function to visualize vector files. Syntax • Plot the vector field Zx and Zy as a function of X and Y quiver(X,Y,Zx,Zy); 54 / 76
  • 55.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Scalar Field and its Gradient • The gradient of a scalar field f (x, y) is defined as f = ∂ ∂x f ∂ ∂y f . • Numerically, we can approximate the partial derivative by ∂ ∂x f (x, y) ≈ f (x + h, y) − f (x, y) h for some small number h. • In Matlab, we can use gradient(F) to find the gradient of the scalar field F. See help for more detail. 55 / 76
  • 56.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Scalar Field and its Gradient −2 −1 0 1 −2 −1 0 1 • Find the gradient of the scalar field f (x, y) = x2 − 3 sin(xy). • Plot f (x, y) using contour(). • Plot its gradient using gradient() in the same figure. 56 / 76
  • 57.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 6 More Plots 57 / 76
  • 58.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Histogram Histogram is useful to visualize the distribution of univariate data. Syntax • Create a histogram of data vector x hist(x); • To specify number of bins, use hist(x,m); 58 / 76
  • 59.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Random Number Generators • Two important random number generators in Matlab: • Uniform between 0 and 1: rand(). • Standard normal: randn(). • Exercise: • Generate N random samples from rand(). • Use hist to visualize the distribution. • Experiment with different N and different number of bins. • How many samples are required to produce a good approximation of it distribution? • Repeat for randn(). 59 / 76
  • 60.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Area, Bar and Pie Chart Syntax • Stacks each data series and fill the underlying area with different colors area(X,Y); • Create a bar chart bar(Y); Each column of Y will have the same color and rows are grouped together. • Pie chart pie(Y); 60 / 76
  • 61.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Operating System War! • Go to http://www.netmarketshare.com/ and download the operating system share trend data (Excel file). • Import it into workspace. • Create the following plots: • Line plot. • Area chart. • Bar chart. • Pie chart on April, 2012. 61 / 76
  • 62.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Scatter Plot Scatter plot is used to visualize the distribution of two dimensional data. Syntax • To generate the scatter plot for the data vector X and Y scatter(X,Y) 62 / 76
  • 63.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Basic Regression • Suppose we are given a data set x and y. • It is assumed that y = ax + b + noise. • Find the best linear fit ˆy = ˆax + ˆb. 0 0.5 1 2 3 4 5 6 x y ˆy = 2.0x + 3.0 63 / 76
  • 64.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Section 7 Extra 64 / 76
  • 65.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Solving Differential Equations • Differential equation involves derivatives of a function in its independent variables. • Almost everything is described by some differential equation. • Mostafa will talk about solving differential equations using powerful tools provided by Matlab. • We can create a poor man’s differential equation solver. • The idea of Finite Difference Method (FDM): ∂u ∂t ≈ u(t + h) − u(t) h for small h. 65 / 76
  • 66.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra The Finite Difference Method • Consider the wave equation utt = c2 ∆u − but, where the Laplacian operator ∆ is defined as ∆u = uxx + uyy . • Use finite difference to approximate derivatives: ut ≈ u(t + ∆t) − u(t) ∆t utt ≈ u(t + ∆t) − 2u(t) + u(t − ∆t) ∆t2 . Similarly for uxx and uyy . 66 / 76
  • 67.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra The Finite Difference Method • In Matlab, we can use the discrete Laplacian function del2 to approximate ∆u ≈ 4 h2 del2(u), where h is the spacing in the spatial grid. • Substitute the derivatives by their finite difference approximation, we get (verify this!) u(t+∆t) ≈ 2u(t)−u(t−∆t)+h2 ∆u(t)−b∆t(u(t)−u(t−∆t)). (3) • Provide the initial data of u and ut at t = 0 and the boundary condition, we can approximate the solution of the wave equation by recursively solving (3). 67 / 76
  • 68.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Demo: 2D Wave Equation −4 −2 0 2 4 −4 −2 0 2 4 0 2 4 6 8 10 Figure: The simulated solution to the wave equation. 68 / 76
  • 69.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Linear Congruential Generator (LCG) • LCG is a popular (and old) Pseudo-Random Numbers Generator. • Simple and efficient to compute. • Poor choice of parameters lead to bad performance. LCG xn+1 ≡ (axn + b) (mod m), (4) • m > 0: the modulus • a > 0: the multiplier • b ≥ 0: the increment • x0: the seed 69 / 76
  • 70.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Histogram 0 10 20 30 0 5 10 15 • Try different parameters and use hist to evaluate its performance. • If you can’t figure out what combination of parameters would work, try • a = 3 • b = 0 • m = 31 • x0 = 1 70 / 76
  • 71.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Polar Plot • Sometimes it is easier to express coordinate in the polar form. • Let (x, y) be the coordinates in the Cartesian coordinate system, its corresponding polar coordinates is given by r = x2 + y2 (5) θ = tan−1 (y/x). (6) Syntax • Plot r versus theta in the polar coordinate polar(theta,r); 71 / 76
  • 72.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Butterfly Curve The butterfly fly curve, discovered by Temple H. Fay, is generated by the equations r = esin θ − 2 cos(4θ) + sin5 2θ − π 24 . (7) 2 4 6 30 210 60 240 90 270 120 300 150 330 180 0 72 / 76
  • 73.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Demo: Lorenz Attractor Lorenz system is a simplified model for atmospheric convection, it is modeled by the ordinary differential equations dx dt = σ(y − x), (8) dy dt = x(ρ − z) − y, (9) dz dt = xy − βz, (10) where x, y and z are the coordinate of the state, t represents time, ρ, σ and β are parameters. 73 / 76
  • 74.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra 3D Line Plot Example Lorenz Attractor −20 0 20 −50 0 50 0 20 40 60 x y z 74 / 76
  • 75.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Visualizing Gibbs’ Phenomena 75 / 76
  • 76.
    2D Plots TheGraphical User Interface Advanced Topics Animation 3D Plots More Plots Extra Exercise: Complex Data as 2D Representation Plot the Hypocycloid. 76 / 76