Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017
Outline
Plotting Functions
Simple Plots
MATLABhasextensivefacilitiesfortheplottingofcurvesandsurfaces,and visualization.
Basic 2D plots of functions and (x,y) pairs can be done with the functions: plot, fplot, ezplot
Simpleplotsofdatapointscanbecreatedusingplot
function y = f(x)
y = exp(-0.5*x).*sin(5*x); end
» x = linspace(0,5,101); » y = f(x);
» plot(x,y);
» xlabel(’x’); % label for axis x » ylabel(’y’);
» grid on; % add major grid lines » title(’f(x) = e^-0.5x sin(5x)’);
Multiple graphs on the same plot
Another example
plot function
Generalform:
plot(x,y, ’specifiers’, ’property’,prop_value)
’specifiers’: color line, line style, marker (or ’clm’ string)
’property’’: line width, marker size, marker color
default values for properties: LineWidth = 0.5points, MarkerSize =
6, FontSize = 10 Example:
plot(x, y, ’b-’,’linewidth’,2,’markersize’,12,…
’markeredgecolor’,’r’, ’markerfacecolor’,’g’);
Color, Line marker, Style
Some examples
x = [1 2 3 4 5 6 7 8 9];
y = [3 4 9 3 5 3 7 5 1];
plot(x,y,’bs-’,…
’MarkerEdgeColor’,’r’, …
’MarkerFaceColor’,’g’)
plot(x,y,’b-’);
Additional option strings
plot(x1,y1,’opt1’, x2,y2,’opt2’, x3,y3,’opt3’);
x1,y1 may have different size than x2,y2 or x3,y3
by default, a new plot command erases the previous plots and reset all
axis properties before drawing the new plot.
hold on/off allows to switch between the default mode (hold off)
and the one which holds the current plot and all axis properties (hold on)
plot(x1,y1,’specs1’,’prop1’,val1); hold on; plot(x2,y2,’specs2’,’prop2’,val3); plot(x3,y3,’specs3’,’prop3’,val3); hold off;
plot(x,y,’b-’, ’LineWidth’,3);
hold on;
plot(x,y,’or’, ’MarkerSize’, 12, ’MarkerFaceColor’,’g’);
Variants of plot
x=N-vector,Y=M×NmatrixorN×Mmatrix
plot(x, Y) – plot the dimension of Y having size N
(columns for M×N, rows for N×M matrix) against x X=M×Nmatrix,Y=M×Nmatrix
plot(X, Y) – plot each column of Y against each column of X
Y=M×Nreal-valuedmatrix
plot(Y) – plot Y columns against their index
Adding text
gtext(’text_string’,’property’,value)-addtext_stringon the graph window at a position chosen by the user (using the mouse)
text(x,y,’text_string’,’property’,value)-addtext_string on the graph window to location (x,y) on the current axes
’property’ can be
fontsize
size of text font
color
text color
fontangle
normal, italic
fontweight
normal, bold
backgroundcolor
rectangular area of text
edgecolor
edge of rectangular box
linewidth
rectangular box
rotation
text orientation
fontname
specify font
These properties can also be used in title, xlabel, ylabel, legend
Example
» x = linspace(0, pi, 100);
» y = sin(x);
» plot(x/pi, y, ’b’, ’linewidth’, 2);
» axis([0, 1, 0, 1.2]); % set xmin, xmax, ymin, ymax
» xlabel(’x/\pi’); % LaTex expressions may be used; here ’\pi’ will be displayed as the Greek symbol π
» text(0.5, 1.05, ’\downarrow MAX at x = \pi/2’,…
’fontsize’, 16, ’fontangle’, ’italic’);
Axis settings
subplot function
Todisplayseveralplotsinthesamegraphicwindow
General form: subplot(m, n, p), where
m×n=boxpattern
p – the rectangle for current plot; it may be a vector of indexes
subplot(3, 4, 2);
subplot(3, 4, 5:6);
subplot(3, 4, [7 8 11 12])
x = linspace(1,10,200);
y1 = sin(x).^2;
y2 = 1./x;
y3 = exp(-0.3*x).*cos(5*x);
y4 = 1./floor(x);
subplot(3,3, 1); plot(x,y1,’b’);
subplot(3,3, 4); plot(x,y2,’r’);
subplot(3,3, [ 2 3 5 6]); plot(x,y3,’m’);
subplot(3,3, 8:9); plot(x,y4,’g’);
subplot
Some of 2D plotting functions
plot
basic x-y plot
fplot
function plot
ezplot
function plot
loglog
log x,y axes
semilogx
log x-axis
semilogy
log y-axis
plotyy
left & right y-axes
polar
polar plot
comet
animated x-y plot
errorbar
plot with error bars
stem, stairs
stem and staircase
scatter
scatter plot
bar,barh
bar graphs
pie
pie chart
histogram
histogram
fill, area
polygon & area fill
fplot, ezplot functions
Ifafunctionf(x)hasalreadybeendefined,itcanbeplottedwithfplot
or ezplot, which are very similar.
General form: fplot(fun, lims, ’specifiers’) to plot the function fun on the axis lims = [xmin, xmax ] or
[xmin, xmax , ymin, ymax ] with the line specification ’specifiers’.
Severalwaystoindicatethefunction
function y = f(x)
y = exp(-0.5*x).*sin(5*x); end
» fplot(@f, [0, 5]); % @f means ’f is the name of a function’
fplot(@sin, [-2,2]*pi, ’r’); fplot(’sin’, [-2,2]*pi, ’r’); fplot(’sin(x)’, [-2,2]*pi, ’r’);
Plotting implicit functions
Using alternative axes
data = 1:1000;
subplot(2,2,1); loglog(data);title(’LOGLOG(1:1000)’); subplot(2,2,2); semilogy(data); title(’SEMILOGY(1:1000)’); subplot(2,2,3); semilogx(data); title(’SEMILOGX(1:1000)’); subplot(2,2,4); plotyy(data,data,data,data.^2); title(’PLOTYY’);
scatter plots Generalform:
Similar with plot(x, y, ’.’), but scatter allows more control of the area and color of dots
Example:aMonteCarlocalculationoftheareaunderthecurveofsin(x),for 0≤x≤π
scatter(x,y, marker_area, marker_color);
N=10000;
x = pi * rand(1,N);
y = rand(1,N);
i = find(y < sin(x));
j = find(y > sin(x));
scatter(x(i),y(i),1,’r’);
hold on;
scatter(x(j),y(j),1,’b’);
x = linspace(0,pi,100); y = sin(x); plot(x,y,’r-’);
A = length(i)/N * pi A=
1.9930 % real value: 2
stem plots
stairs plot
x = linspace(0, 40, 41);
y = sin(x/5);
stairs(x, y, ’b’);
bar graphs
Y =[8 1 2; 9 3 9; 2 5 9; 9 7 5; 6 9 8]; x = 2007:2011; y = Y(:,2); subplot(2,2,1); bar(x,y); subplot(2,2,2); bar(x,Y); subplot(2,2,3); barh(Y); subplot(2,2,4); bar(Y);
histogram plot
rng(101); % initialize random generator
b = 0:5:100; % define bins
g = ceil(70 + 12 * randn(1,600)); % simulate 600 random grades figure; % generate a new graphic window
histogram(g, b);
axis([0, 105, 0, 105]);
title(’grade distribution’);
pie charts
Na = length(find(g>=90)); % number of A grades
Nbp = length(find(g<90 & g>=85)); % number of B+ grades Nb = length(find(g<85 & g>=75));
Ncp = length(find(g<75 & g>=70));
Nc = length(find(g<70 & g>=60));
Nd = length(find(g<60 & g>=50));
Nf = length(find(g<50));
N = [Nf, Nd, Nc, Ncp, Nb, Nbp, Na];
pie(N);
pie(N, {’F’,’D’,’C’,’C+’,’B’,’B+’,’A’});
3D plotting functions
plot3
x-y-z line plot
contour
contour plot
contourf
filled contour plot
mesh
wireframe surface plot
meshc
wireframe plus contour
surf
solid surface plot
surfc
surface plot plus contour
waterfall
waterfall plot
stem3, scatter3
3D stem and scatter
bar3, bar3h, pie3
3D bar & pie charts
fill3
polygon fill
comet3
animated plot3
meshgrid function
A function of two variables, f(x,y) define a surface
meshgrid(x,y)generatesarectangulargridinthex-yplanestarting from two vectors x and y
» x = [-2:2]; y = [3:5]; » [X, Y] = meshgrid(x,y) X=
-2 -1 0 1 2 -2 -1 0 1 2 -2 -1 0 1 2
Y= 33333 44444 55555
meshgrid & ngrid
meshgrid & ngrid
mesh function
x = linspace(-5,5,51);
y = linspace(-5,5,51);
[X,Y] = meshgrid(x,y);
Z = Y .* exp(-(X.^2 + Y.^2)/2); mesh(X,Y,Z);
surf function
x = linspace(-5,5,51);
y = linspace(-5,5,51);
[X,Y] = meshgrid(x,y);
Z = (X.^2 + Y.^2) .* exp(-(X.^2 + Y.^2)/2);
surf(X,Y,Z);
shading interp;
colorbar;
surf(X,Y,Z);
colorbar;
Reading & writing image files
Toreadanimagefile: or
Towriteanimagefile:
Thefileextensionfmtmaybe’jpg’,’jp2’,’tiff’,’png’,’gif’,’bmp’,andothers Thesefunctionshaveadditionalinput/outputoptions
A = imread(filename, fmt);
[A, map] = imread(filename, fmt);
imwrite(A,filename,fmt);
s1 = ’https://upload.wikimedia.org’; s2 = /wikipedia/commons/d/de/’;
s3 = ’St_Louis_night_expblend.jpg’; filename = [s1 s2 s3];
y = imread(filename,’jpg’); image(y);axis off;
y = imread(’ngc6543a.jpg’, ’jpg’); image(y);
title(’NGC 6543 Nebula’); axis off;