Graphic Objects
Graphics objects are the basic drawing elements used by MATLAB to display data.
Each instance of an object has a unique identifier called a handle.
Using this handle, you can manipulate the object properties of an existing graphics object.
set changes the property of the object.
get returns the property of the object. (Try.)
figure creates figure graphics objects using default property values. (Try.)
Graphic Object Hierarchy
11See p. 293, Lent.
Example: Set Figure Size
1 screen size = get(0, 'ScreenSize') % 0: the screen
2 figure('Position', [1 screen size(4)/2 ...
screen size(3)/2 screen size(4)/2]);
Seeaccessing-object-handles.
The current figure, denoted by gcf, is the window designated to receive graphics output.
The current axes, denoted by gca, are the targets for commands that create axes children.
The current object, denoted by gco, is the graphics object created or clicked on by the mouse.
Example
1 clear all;
2 clc
3 % main
4 x = -0.5*pi:0.01*pi:0.5*pi;
5 h = plot(x,sin(1./x)); % plot a sin curve
6 set(h,'marker','o'); % set marker to 'o'
7 set(h,'markerSize',5); % set marker size to 5
8 set(h,'lineWidth',1.5); % set line width to 1.5
9 set(h,'lineStyle',':'); % set line style to dot
10 set(h,'markerEdgeColor','r'); % set marker edge ...
color to green
11 set(h,'markerFaceColor','g'); % set marker face ...
color to yellow
You can use theplot toolin the figures to change the properties.
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
−1
−0.8
−0.6
−0.4
−0.2 0 0.2 0.4 0.6 0.8 1
Axis (1/3)
plot automatically decides the ranges of axis.
axis([xmin, xmax , ymin, ymax ]) sets the ranges of the current axes.
1 clear; clc;
2 % main
3 x = 0:0.1:4*pi;
4 y = sin(x);
5 plot(x,y);
6 grid on;
7 axis([-inf, inf, -0.5, 2]); % [xmin xmax ymin ymax]
0 2 4 6 8 10 12
−0.5
−0.4
−0.3
−0.2
−0.1 0 0.1 0.2 0.3 0.4 0.5
Axis (2/3)
axis autois the default setting.
axis tightmakes the axes shape to conform to the plotted data.
axis equalmakes the x- and y-data units equal.
axis squaremakes the x- and y-axes equal in length.
Axis (3/3)
Change the location of the tick marks on the plot by setting xtick and ytick of the axes.
Use gca to set the properties for the current axes.
1 clear all;
2 clc
3 % main
4 x = 0:0.1:4*pi;
5 plot(x,sin(x)+sin(3*x));
6 axis tight;
7 set(gca,'ytick',[-1 -0.3 0.1 1]);
8 set(gca,'yticklabel',{'Min','Threshold','Critical ...
Point','Max'});
9 grid on;
Try ’xtick’ and ’xticklabel’.
0 2 4 6 8 10 12 Min
Threshold Critical Point Max
subplot
Multiple plots can be placed in the same figure.
subplot(m, n, p) divides the current figure into an m-by-n grid and creates an axes in the grid position specified by p.
For example,
1 clear; clc;
2 % main
3 x = 0:0.1:4*pi;
4 subplot(2,2,1);plot(x,sin(x));title('Subplot 1');
5 subplot(2,2,2);plot(x,cos(x));title('Subplot 2');
6 subplot(2,2,3);plot(x,sin(x).*exp(-x/5));
7 title('Subplot 3');
8 subplot(2,2,4);plot(x,x.ˆ2);title('Subplot 4');
9 grid on;
0 5 10 15
−1
−0.5 0 0.5 1
Subplot 1
0 5 10 15
−1
−0.5 0 0.5 1
Subplot 2
0 5 10 15
−0.5 0 0.5 1
Subplot 3
0 5 10 15
0 50 100 150 200
Subplot 4
Summary: Line Plots
plot 2-D line plot
plotyy 2-D line plots with y-axes on both left and right side loglog Log-log scale plot
semilogx Semilogarithmic plot semilogy Semilogarithmic plot errorbar Plot error bars along curve
fplot Plot function between specified limits ezplot Easy-to-use function plotter
Summary: More Plots
bar Bar graph
barh Plot bar graph horizontally hist Histogram plot
rose Angle histogram plot pareto Pareto chart
area Filled area 2-D plot pie Pie chart
stem Plot discrete sequence data stairs Stairstep graph
scatter Scatter plot
contour Contour plot of matrix
bar
2bar(x , y , ’style’) draws bars for each column in y at locations specified in x , and ’style’ specifies the style of the bars.
For example,
1 Clear all; clc;
2 x = 1900:10:2000;
3 y = [75.995,91.972,105.711,123.203,131.669,...
4 150.697,179.323,203.212,226.505,249.633,281.422];
5 bar(x,y);
2Seebar.
1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 0
50 100 150 200 250 300
Example: Available Styles
1 clear; clc;
2
3 y = round(rand(5,3)*10);
4 figure;
5 subplot(2,2,1);
6 title('Group');
7 bar(y,'grouped');
8
9 subplot(2,2,2);
10 title('Stack');
11 bar(y,'stacked');
12
13 subplot(2,2,3);
14 title('Histc');
15 bar(y,'histc');
16
17 subplot(2,2,4);
18 title('Baseline');
19 h = bar(y, 'LineWidth',1 ,'EdgeColor', 'red', ...
'LineStyle', ':');
1 2 3 4 5 0
2 4 6 8 10
Group
1 2 3 4 5
0 10 20 30
Stack
1 2 3 4 5
0 2 4 6 8 10
Histc
1 2 3 4 5
0 2 4 6 8 10
Hist
plotyy
plotyy(x 1, y 1, x 2, y 2) plots x 1 versus y 1 with y-axis labeling on the left and plots x 2 versus y 2 with y-axis labeling on the right.
For example,
1 clear all; clc;
2 x=0:0.01:20;
3 y1=200*exp(-0.05*x).*sin(x);
4 y2=0.8*exp(-0.5*x).*sin(10*x);
5 plotyy(x,y1,x,y2);
0 5 10 15 20
−200
−150
−100
−50 0 50 100 150 200
0 5 10 15 20−0.8
−0.6
−0.4
−0.2 0 0.2 0.4 0.6 0.8
errorbar
errorbar(x , y , e) plots y versus x with symmetric error bars 2 × e(i ).
1 clear; clc;
2 % main
3 x = linspace(0,2*pi,30);
4 y = sin(x);
5 e = y*0.2;
6 errorbar(x,y,e);
7 grid on;
−1 0 1 2 3 4 5 6 7
−1.5
−1
−0.5 0 0.5 1 1.5
fplot
fplot(fun, limits) plots a function3 between specified limits.
1 clear; clc;
2 % main
3 fplot('sin(1/x)', [0.02 0.2]);
4 grid on;
Try ezplot.
0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0.2
−1
−0.8
−0.6
−0.4
−0.2 0 0.2 0.4 0.6 0.8 1
polar
polar(θ, r ) creates a polar coordinate plot of the angle θ versus the radius r .
1 clear; clc;
2 % main
3 theta = linspace(0,2*pi);
4 r = cos(4*theta);
5 polar(theta,r,'-r');
6 grid on;
0.2 0.4
0.6 0.8
1
30
210
60
240
90
270 120
300 150
330
180 0
hist
hist(y ) creates a histogram bar plot of y .
Elements in y are sorted into 10 equally spaced bins along the x-axis between the minimum and maximum values of y .
1 clear; clc;
2 % main
3 n = 1e5;
4 nbins = 1e2; the number of bins
5 subplot(2,1,1); hist(rand(1,n),nbins);grid on;
6 title('Uniform distribution');
7 subplot(2,1,2); hist(randn(1,n),nbins);grid on;
8 title('Normal distribution');
0 0.2 0.4 0.6 0.8 1 0
500 1000 1500
Uniform distribution
−5 0 5
0 1000 2000 3000 4000
Normal distribution
3D-Plotting by mesh
mesh(X , Y , Z ) plots the colored mesh defined by 3 matrix arguments.
1 clear; clc;
2 % main
3 x = 3:6; % the range along the x-axis
4 y = 5:9; % the range along the y-axis
5 z = zeros(length(y),length(x));
6 for i = 1:size(z,1)
7 for j = 1:size(z,2)
8 z(i,j) = y(i)*x(j); % z = f(x,y)
9 end
10 end
11 mesh(x,y,z);
12 xlabel('X');ylabel('Y');zlabel('Z');axis tight;
3
4
5
6
5 6 7 8 9 20 30 40 50
Y X
Z
3D-Plotting by surf
surf(X , Y , Z ) plots the colored surface defined by 3 matrix arguments.
[X , Y ] =meshgrid(x , y ) transforms the domain specified by vectors x and y into arrays X and Y that can be used for the evaluation of functions of two variables and 3-D surface plots.
You may try meshz, meshc, surfc, and waterfall.
Example: z = xe
−(x2+y2)1 clear; clc;
2 % main
3 x = linspace(-2,2,25);
4 y = linspace(-2,2,25);
5 [xx,yy] = meshgrid(x,y); % form all x-y pairs
6 zz = xx.*exp(-xx.ˆ2-yy.ˆ2);
7 surf(xx,yy,zz);
−2
−1 0
1 2
−2
−1 0 1 2
−0.5 0 0.5
Exercise: sinc(x ) = sin(x ) x
There is a singularity point at x = 0.
In order to avoid this infinity, one can add an eps in the equation.
eps = 2.22044604925031e − 016
1 [X,Y]=meshgrid(-8:.5:8);
2 R=sqrt(X.ˆ2+Y.ˆ2)+eps;
3 Z=sin(R)./R;
4 surf(Z);
0
10 20
30 40
0 10 20 30 40
−0.5 0 0.5 1
plot3
plot3(x , y , z), where x , y and z are three vectorsof the same length, plots a curve in 3-dimensional coordinate through the points.
For example,
1 clear; clc;
2 % main
3 t = 0:0.1:10*pi;
4 plot3(t.*sin(t),t.*cos(t),t);
5 hold on;
6 plot3(t.*sin(t),t.*cos(t),-t,'r');
7 axis equal;
8 grid on;
−20 0
20
−20 0 20
−30
−20
−10 0 10 20 30
Example: z = xe
−(x2+y2)(Revisited)
We can plot z(x , y ) by plot3.
1 clear; clc;
2 % main
3 [x,y] = meshgrid(-2:0.1:2);
4 z = x.*exp(-x.ˆ2-y.ˆ2);
5 plot3(x,y,z); grid on;
−2
−1 0
1 2
−2
−1 0 1 2
−0.5 0 0.5
griddata
In practice, the data points are collected from the measurement in experiments.
Oneposterior analysis on these data points is to find the possible curves or surfaces to fitthe observed data points.
griddata interpolates the surface at the query points specified by (xq, yq) and returns the interpolated values.
griddata(x , y , v , xq, yq) returns a fitted surface of the form v = f (x , y ) to the scattered data in the vectors (x , y , v ).
peaks
peaks(x , y ) returns a matrix of the function values, given by z = 3(1−x )2e−x2−(y +1)2−10(x
5−x3−y5)e−x2−y2−1
3e−(x+1)2−y2. One can simply execute peaks to obtain a figure. (Try.)
Example
1 clear; clc;
2 % main
3 x = 6*rand(100,1)-3;
4 y = 6*rand(100,1)-3;
5 z = peaks(x,y); % 100 sample points in total
6 [xq,yq] = meshgrid(-3:0.1:3);
7 zq = griddata(x,y,z,xq,yq,'cubic');
8 % Choose the linear, cubic, or nearest method to ...
interpolate.
9 mesh(xq,yq,zq); hold on;
10 plot3(x,y,z,'.','markersize',16); axis tight;
−3 −2 −1 0 1 2 3
−2 0 2
−6
−4
−2 0 2 4 6
3-D Graph Viewpoint Specification
view(AZ , EL) sets the angle of the view from which an observer sees the current 3-D plot.
AZ is the azimuth or horizontal rotation.
EL is the vertical elevation.
Note that AZ and ZL are both in degrees.
You can use the Rotate 3D button in the figure.
1 clear; clc;
2 % main
3 peaks;
4 view([60,-15]); % degree
5 colorbar % Appends a colorbar to the current axes
−2 0
2
−3 −2 −1 0 1 2 3
−6
−4
−2 0 2 4 6 8
x Peaks
y
−6
−4
−2 0 2 4 6 8
colormap
Save Figures
In the menu of figure, you can save as any file type of picture file.
Exporting to Files
print(gcf,’-fileType’,’fileName’) saves the contents of the current figure with a specified file type and file name.
For example,
1 clear all;
2 clc;
3 % main
4 surf(peaks);
5 print(gcf,'-djpeg','peaks.jpg');
You can find more optional argumentshere.
Exercise: Save to Multiple Files
1 clear all;
2 clc;
3 filename set={'file1', 'file2', 'file3'};
4 for i=1:length(filename set)
5 surf(sphere(i*10));
6 print('-djpeg',fnames{i});
7 end
Solution
0
10 20
30 40
0 10 20 30 40
−1
−0.5 0 0.5 1
A Love Tale: Cardioid
傳聞,法國著名數學家笛卡爾(Descartes)曾經流落到瑞典,
邂逅瑞典公主Kristina,並成為了公主的數學老師。兩人萌
生愛意。國王知道後,強行拆散他們,並且沒收了之後笛卡 爾寫給公主的所有信件。
後來,笛卡爾染上黑死病,臨死前給公主寄去了最後一封 信,信中只寫著一行字:
r = a(1 − sin(θ))
國王和大臣們都看不懂這是什麼意思,只好交還給公主。
公主在紙上建立了極坐標系,用筆在上面描下方程的點,看 到了方程所表示的心臟線(Cardioid),理解了笛卡爾對自己 的深深愛意。
1 clear; clc;
2 % main: by polar
3 a = 2;
4 theta = 0:0.05:2*pi;
5 rho = a*(1 - sin(theta));
6 polar(theta,rho,'r*'); grid on;
1 2
3 4
30
210
60
240
90
270 120
300 150
330
180 0
3D Heart
1 clear; clc;
2 % main
3 [X Y Z] = meshgrid(-3:0.1:3, -3:0.1:3, -3:0.1:3);
4 F = ((-(X.ˆ2).*(Z.ˆ3)-(9/80).*(Y.ˆ2).*(Z.ˆ3))...
5 +((X.ˆ2)+(9/4).*(Y.ˆ2)+(Z.ˆ2)-1).ˆ3);
6 p = patch(isosurface(X,Y,Z,F,0));
7 set(p,'facecolor','w','EdgeColor','r'); % graphic ...
handling
8 daspect([1 1 1]);
9 axis tight; axis equal;
10 view(3); % set the default 3-D view, AZ = -37.5, ...
EL = 30.
−1
−0.5 0
0.5 1
−1
−0.5 0 0.5 1
−1
−0.5 0 0.5 1
Animation
Animation is the process of creating motion and shape change illusion by means of the rapid display of a sequence of static images that minimally differ from each other.
Simply put, images are displayed in a rapid succession, usually 24, 25, 30, or 60 frames per second.
movie Play recorded movie frames comet 2-D comet plot
getframe Capture movie frame
im2frame Convert image to movie frame
frame2im Return image data associated with movie frame
Example
1 function starpoly(n,step)
2 y = zeros(1,n);
3 for k = 0:n
4 y(k+1) = ...
cos(2*pi/n*(step*k))+i*sin(2*pi/n*(step*k));
5 end
6 plot(y,'bo-'); axis equal; hold off;
7 end
1 clear; clc;
2 % main
3 t = 0:0.01:2*pi;
4 for k = 1:1:50*pi
5 plot(cos(t) + i*sin(t),'r--'); hold on;
6 starpoly(79,k);
8 frame = getframe(1);
9 im = frame2im(frame);
10 [imind,cm] = rgb2ind(im,256);
11 if k == 1
12 imwrite(imind, cm, 'go.gif', 'gif', ...
'Loopcount', inf);
13 else
14 imwrite(imind, cm, 'go.gif', 'gif', ...
'writemode', 'append');
15 end
16 end
1 >> Lecture 5
2 >>
3 >> -- Matrix Computation
4 >>
Vectors
We denote the vector space of all m-by-1 column vector x by Rm×1:
x ∈ Rm×1↔ x = (xi) =
x1
... xm
. (1)
Similarly, the row vector ~y is in form of y ∈ R1×n ↔ y = (yi) =
y1· · · yn . (2)
Matrices
Let R be the set of all real numbers.
We denote the vector space of all m-by-n real matrices A by Rm×n:
A ∈ Rm×n ↔ A = (aij) =
a11 · · · a1n
... . .. ... am1 · · · amn
.
Recall the matrix indexing4. By subscripts: A(i , j )
By linear addressing: A(k) for some positive integer k.
The matrix definition is similar if we consider complex matrices.
Transposition
transpose(A) is the transpose of A.
1 A=magic(4)
2 transpose(A)
You can also transpose A by
1 A'
Note that if A ∈ Cm×n, then A’ is the transposition and complex conjugate5 of A.
5z = a + bi has a complex conjugate ¯z = a − bi .
Arithmetic Operations
Addition and subtraction are the same both for vectors and matrices.
Let aij, bij be the elements of the matrices A, B ∈ Rm×n for 1 ≤ i ≤ m and 1 ≤ j ≤ n.
Then C = A ± B can be calculated by cij = aij± bij. (Try.) For vectors,
inner product6 is a binary operation which takes two vectors and returns a scalar quantity.
cross product7 is a binary operation which takes two vectors and returns another vector perpendicular to both two vectors.
Inner Product
8Let A, B ∈ Rm×1 be two column vectors. Then the inner product of A · B =
a1· · · am
b1
... bm
.
8Seeinner product
Example
1 clear all;
2 clc
3 % main
4 x=[1;2;3];
5 y=[4;5;6];
6 z=0;
7 for i=1:3
8 z=z+x(i)*y(i);
9 end
10 z % by definition using a for loop
11 x'*y % equivalent formula
12 dot(x,y) % using built-in function
Exercise
Write a program that returns the angle between vectors x and y .
Input: vectors x , y Output: θ in degree
Solution
1 function theta = myAngle(x,y)
2 % input: two vectors x,y
3 % output: angle in degree
4 len x = sqrt(sum(x.ˆ2));
5 len y = sqrt(sum(y.ˆ2));
6 theta = acos(x'*y/len x/len y)/pi*180;
1 >> x = [1/sqrt(2);0;1/sqrt(2)];
2 >> y = [1/sqrt(2);1/sqrt(2);0];
3 >> myAngle(x,y)
4
5 ans =
6
7 60
Cross Product
cross(x , y ) returns the cross product of the vectors x and y . Note that x and y must be 3-dimensional vectors.9
For example,
1 >> x=[1;0;0];
2 >> y=[0;1;0];
3 >> z=cross(x,y) % built-in
4
5 z =
6
7 0
8 0
9 1
9Actually, only in 1-, 3-, and 7-dimensional Euclidean spaces.