Upload
jbarragan
View
43
Download
10
Embed Size (px)
DESCRIPTION
Tercera parte del curso de Matlab de la universidad de Lovaina (Bélgica), gráficas en 2D.
Citation preview
MATLABhi 2Dgraphics 2D
Content/purposep p
C• Content– Elementary 2D-graphs
– Axes and more
– More 2D-graphs
• learn some of the basic plotting functions in Matlab
• provide simple examples to get started
• IMPORTANT: play around with the examples and experiment as much as possible, p preading this text is not enough!
Graphics2D_2
plotting your datap g y• If only
previewing or1. Prepare your data x = 0:0.2:12;
1 b l(1 )previewing or exploring data, steps 1 and 3 may be all you
d
y1 = bessel(1,x);
y2 = bessel(2,x);
2. Select a window and figure(1)need.
• If creating presentation graphics you
position a plot region within the window
g
subplot(2,2,1)
graphics, you may want to finetune your graph by
3. Call elementary plotting
function
h = plot(x, y1, x, y2)
g p ypositioning it on the page, setting line styles and
4. Select line and marker
Characteristics
set(h,'LineWidth',2,{'LineStyle'},…
{'--';':'})
set(h {'Color'} {'r';‘b'})styles and colors, adding annotations,and making other
Characteristics set(h,{ Color },{ r ; b })
5. Set axis limits, tick
marks, and grid lines
axis([0 12 -0.5 1])
grid ongsuch improvements.
• ex. first_plot
marks, and grid lines
6. Annotate the graph
ith i l b l l d
xlabel ('Time')
l b l ('A lit d ')
Graphics2D_3
with axis labels, legend and text
ylabel ('Amplitude')
legend(h,'First','Second')
basic plotsp
M l b h dl f 2D d 3D l• Matlab can handle most types of 2D and 3D plots without having to use Handle Graphics
• start with: help graph2d (Two dimensional graphs.)
(Th di i l h )help graph3d (Three dimensional graphs.)help specgraph (Specialized graphs)
d t i f ti i th h l i dand get more information in the help window
Graphics2D_4
figureg
fi f d l i f l i• figure: fundamental container for plotting
Graphics2D_5
plot commandp
l t th l f Y th i• plot(Y): plots the columns of Y versus their index if Y is a real number.
• plot(X1,Y1,...): plots all lines defined by Xn versus Yn pairsXn versus Yn pairs.
• plot(X1,Y1,LineSpec,...): plots all lines defined by the Xn,Yn,LineSpec triples, where LineSpec is a line specification for line type, p p ypmarker symbol, and color of the plotted lines.
• plot( 'PropertyName' PropertyValue• plot(..., PropertyName ,PropertyValue,..): sets properties to the specified property
l f ll li hi bj t t d bvalues for all line graphics objects created by plot.
plot: line specsp p
li ifi tiline specifications:• LineStyle:
lid li (d f lt)- solid line (default)--dashed line:dotted line:dotted line-. dash-dot line
• Marker: Marker symbolMarker: Marker symbol. + o * . x(cross) s(square) d(diamond) ^ > < p(pentagram) h(hexagram)
• Color:y m g r c b (=blue) k (= black) w
Graphics2D_7
plotp
• ex. l t2D i lplot2D_simple.m
plot2D_simple_02.m
x=0:0.05:5;y=sin(x.^2);plot(x,y);
plot(x,y,'--rs',... 'Li Width' 2'LineWidth',2,... 'MarkerEdgeColor','k',...'MarkerFaceColor','g',...'M k Si ' 10)
Graphics2D_8
'MarkerSize',10)
Extra information
l b l l b l l b l• xlabel, ylabel, zlabel:– Label the x-, y-, and z-axis
• title:– places a title on your plot
• legend:– adds a legend to
your plot
• ex. plot2D_extra
Graphics2D_9
Extra information
• text:– creates a text object
in c rrent a esin current axes
• grid on/offdd / id li– adds/removes grid lines
• box on/off– adds/removes axes box
• ex. plot2D_extra2.m
Graphics2D_10
axes control
A i li dAxis scaling and appearance• axis([xmin xmax ymin ymax]): sets the
limits for the x- and y-axis of the current axis• axis auto : default behavior of computing theaxis auto : default behavior of computing the
current axes' limits automatically, • axis tight: sets the axis limits to the range• axis tight: sets the axis limits to the range
of the data.i di i• axis square:square dimensions
• axis equal: equal unit spacing on x and y axes; ensures correct aspect ratio
• axis off: hides the axes, tickmarks, labels, ,• ex: plot2D_axis.m
backgroundg
hit b• whitebg– Change axes background color
Set the background color to blue gray whitebg([0 5 6])– Set the background color to blue-gray. whitebg([0 .5 .6])– Set the background color to blue. whitebg('blue')
• Rem: resetting the default background:Rem: resetting the default background:% reset the defaults
reset(0);colordef white;
Graphics2D_12
multiple graphsp g p
I th h ld• In the same axes: hold on
• In the same window: subplot
• In different windows: figure
• Change between windows: figure(figure number)g g ( g _ )
• Clear the graphics: clf, cla
• Close a window: close(figure number) close• Close a window: close(figure_number), close all
l t2D lti l• ex. plot2D_multiple.m
Graphics2D_13
subplotp
lti l l t b t i 1 fi i b l• multiple plots can be set in 1 figure using subplot
• subplot(m,n,p) creates an axes in the pth pane of a figure divided into an m-by-n matrix f t lof rectangular
panes.
• ex. plot2D_subplot.m
Graphics2D_14
Choosing a good chartg g
B f ti h t k lf h t t d I d t• Before creating a chart, ask yourself: what story do I need to tell?
• Graph works best when the message is contained in the shape of the data (patterns, trends, exceptions, ...) (Stephen Few)
• Chart-Thought-Starter (Andrew Abela- extremepresentation.typepad.com)
• Check MATLAB Blog (http://blogs.mathworks.com/videos/2009/01/16/flow-chart-shows-g ( p gwhich-visualization-to-use/)
• Check also MATLABcentral
Relationship plotsp p
S l• Scatter plot– type of display using Cartesian coordinates to display values for
t o ariables for a set of datatwo variables for a set of data.
– gives an idea of the relation between the two variables.
Matlab functions:– Matlab functions:• plot
• scatter
• Bubble plot– similar to the scatter plot in which data are plotted on a two-p p
dimensional x and y axis coordinate system. The difference is that a third data factor (z) controls the size / color of the scatter pointspoints.
– Matlab functions:• scatterscatter
Scatter plotp
i h h h l i hi h i l i l• either shows the relationships among the numeric values in several data series, or plots two groups of numbers as one series of XY coordinates. • commonly used for scientific data.• arrange the data: place x values in one row or column, and then enter
di l i th dj t lcorresponding y values in the adjacent rows or columns.•Chart2D_scatter_01
Scatter plotp
N 50 % N b f d t i tN = 50; % Number of data points
% generate the data
xdat = rand(1,N);
ydat = rand(1,N);
% use the plot function
% specify the marker and no line style to draw only points
figure;
plot(xdat, ydat, 's');p ( , y , )
% use the scatter function
fig refigure;
scatter(xdat, ydat);
Bubble plotp
B bbl l ll h h i h l f• Bubble plots allow to change the size, shape, or color of each data point.
• Let the size or color of the plotted points represent an additional variable.
• scatter
• Chart2D bubble 01_ _
Bubble plotp
N 10 % N b f h t lN = 10; % Number of charges to place
xq=rand(1,N); % x positions of the charges
yq=rand(1,N); % y positions of the charges
q=100*rand(1 N)-50; % magnitude of charges (between -50 and 50)q=100 rand(1,N) 50; % magnitude of charges (between 50 and 50)
color = 1.5+sign(q)/2; % sign(q) returns 1 or -1, so color is 1 2or 2
size = abs(q)*100; % Make size of points bigger for bigger magnitude of q
scatter(xq,yq,size,color,'filled');( q,yq, , , );
hold on; % add another plot on top
l t( ' +' 'M k Si ' 10) % dd i th t fplot(xq, yq,'w+','MarkerSize',10) % add a cross in the center of the circles
2D plotsp
l t f i t• plot arrays of points– Basics
• plot: line-plotsloglog, semilogx, semilogy: change the axis
More– More• polar: polar coordinates• area, fill: surfacearea, fill: surface• stairs: stair plot• bar, pie: diagrams• contour, contourf: isolines• quiver: vector fields• gradient: utilities
• plot functions, not just arrays of points
Graphics2D_22– fplot, ezplot
polar - semilogp g
• polar(theta,rho) • semilogx and pcreates a polar coordinate plot of the
gsemilogy plot data as logarithmic scales forcoordinate plot of the
angle theta versus the radius rho
logarithmic scales for the x- and y-axis,
ti l l ith iradius rho.
• ex. plot2D_polar.mrespectively. logarithmic
• ex. plot2D_semilog.mp _ g
Graphics2D_23
loglogg g
• loglog plots data on a g g plog-log scale
• ex plot2D loglog m• ex. plot2D_loglog.m
Graphics2D_24
area - stairs
• area(Y) Area fill of a • stairs(Y) draws a two-dimensional plot.
• ex plot2D area m
( )stairstep plot of the elements of Y• ex. plot2D_area.m elements of Y.
• ex. plot2D_stairs.m
Graphics2D_25
bar - piep
• A bar chart displays the • pie(X) draws a pie p yvalues in a vector or matrix as horizontal or
p ( ) pchart using the data in X pie(X explode)matrix as horizontal or
vertical bars.
l t2D b
X. pie(X,explode)offsets a slice from the
i• ex. plot2D_bar.m pie.
• ex.plot2D_pie.mp _p
Graphics2D_26
contour - contourf
• contour displays 2-D • contourf displays p yisolines generated from values given by a matrix
p yisolines and fills the areas between thevalues given by a matrix
Z.
l t2D t
areas between the isolines using constant
l• ex. plot2D_contour.m colors. ex.plot2D_contourf.m
Graphics2D_27
quiverq
• quiver: displays q p yvelocity vectors as arrows with components (U V) atwith components (U,V) at the points (X,Y).
l t2D i• ex. plot2D_quiver.m
Graphics2D_28
stem
• For discrete-time signals, use the command stemwhich plots each point with a small open circle and a straight line.
• plot y[k] versus k: stem(k,y)
• use stem(k,y,'filled')to get circles that are filled
• ex. plot2D stem.mp _
Graphics2D_29
compassp
t l t th t di l th l d• compass: generates a plot that displays the angle and magnitude of of vectors
Graphics2D_30
errorbar
b• errorbar
• Plot error bars along a curveError bars show the confidence level of data or the deviation along a curve.
• ex. plot2D_errorbar.m
Graphics2D_31
paretop
Th h d l i h• The pareto charter draws values in the vector argument as bars in descending order along with the associate
l t d li l taccumulated line plot.
• PARETO(Y,NAMES) produces a Pareto chart. Each bar will be labeled with the
i t dassociated name in the string matrix
ll NAMESor cell array NAMES.
Graphics2D_32
boxplotp
• an efficient method for displaying a five-number data summary:number data summary:– median
d l– upper and lower quartiles
– minimum and maximum data values
• boxplot(X) produces a box and whisker plot a bo a d s e p otfor each column of the matrix X
Graphics2D_33
matrix X.
• ex. plot2D_boxplot
hist
• n = hist(Y) bins the elements in vector Y into 10 equally spacedinto 10 equally spaced containers and returns the number of elementsthe number of elements in each container as a
trow vector.
• ex. plot2D histogram.mp _ g
Graphics2D_34
fill
fill fill d 2D l• fill : filled 2D polygons
• A polygon described by a set of vertices can be drawn and filled in using the
• fill function
• ex. plot2D_fill.m
Graphics2D_35
plotyyp yy
• Plotting with Two Y-gAxes
• plotyy: create plots• plotyy: create plots of two data sets and
b th l ft d i htuse both left and right side y-axes. apply different plotting functions to each data set; combine a line plot with a stem plot of thewith a stem plot of the same data.
Graphics2D_36• ex. plot2D_plotyy.m
fplotp
f l l t f ti d fi d b f ti• fplot plots a function defined by a m-function or function handles.Th f ti t b f th f f( ) h iThe function must be of the form y = f(x), where x is a vector whose range specifies the limits
d ti l• fplot adaptively determines th li tthe sampling rate
• ex. plot2D_fplot.m
Graphics2D_37
ezplotp
• ezplot: plot functions p pdefined by function handles stringhandles, string expressions.
d t h t• user does not have to specify the data of the independent variable.
• ex: plot2D ezplot.mex: plot2D_ezplot.m
Graphics2D_38
ezplotp
• ezplot: plot functions p pdefined by function handles stringhandles, string expressions.
d t h t• user does not have to specify the data of the independent variable.
• ex: plot2D ezplot.mex: plot2D_ezplot.m
Graphics2D_39
MATLABhi 3Dgraphics 3D
3D visualisation
1. prepare your data z = peaks(20);1. prepare your data
2. select window and figure(1);
subplot(1, 1, 1);
position plot regionp ( , , );
3 call 3-D graphing h = surf(z)3. call 3 D graphing function
4 l d h di colormap hot;4. set colormap and shading algorithm
colormap hot;
shading interp;
set(h, ‘EdgeColor’, ‘k’);
5. add lighting light(‘Position’,[-2, 2, 20]);
lighting phong material ([0.4,0.6,0.5,30])([0.4,0.6,0.5,30])
set (h, ‘FaceColor’, [0.7 0.7 0],’BackFaceLighting’,’lit’)
Graphics3D_2
3D visualisation
6. set viewpoint view([30, 25]);6. set viewpointset(gca, ‘CameraViewAngleMode’,’Manual’);
7 set axis limits and tick axis([0 20 0 20 -10 10]);7. set axis limits and tick marks
set (gca, ‘Zticklabel’, ‘Negative || Positive’)
8. set aspect ratio set(gca, ‘PlotBoxAspectRatio’,[2.5 2.5 1]);
9. annotate the graph xlabel(‘X Axis’);
ylabel(‘Y Axis’);
zlabel(‘ Function’);zlabel( Function );
title (‘Peaks’);
ex. first_plot3D.m
Graphics3D_3
Domain generation: meshgridg g
3D l f( )• 3D-plots: z=f(x,y)
• The first step in displaying a function of two variables, z = f(x,y), is to generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function.
• The meshgrid function transforms the domain specified by two vectors, x and y, into matrices, X and Y
Graphics3D_4
meshgridg
C t f h i ( ) b iti d• Compute z for each pair (x, y) by writing down a loop
• meshgrid provides the appropriate matrix• X =[ -1 0 1]X [ 1 0 1]
y = [9 10 11 12][X, Y] = meshgrid(x, y)[X, Y] meshgrid(x, y) returnsX = Y=X Y - 1 0 1 9 9 9 - 1 0 1 10 10 101 0 1 10 10 10 - 1 0 1 11 11 11 - 1 0 1 12 12 121 0 1 12 12 12
• ex. plot3D_meshgrid.m
plot3p
l 3 di l th di i l l t f t f d t• plot3 displays a three-dimensional plot of a set of data points.
• ex. plot3D_plot3_1.m
Graphics3D_6
mesh / surf
Th d d t 3 D• The mesh and surf commands create 3-D surface plots of matrix data. Z(i,j) define the height of a surface over an underlying (i,j) grid, then:underlying (i,j) grid, then:– mesh(Z) generates a colored, wire-frame view of
the surface and displays it in a 3-D viewthe surface and displays it in a 3-D view. – surf(Z) generates a colored, faceted view of the
surface and displays it in a 3 D viewsurface and displays it in a 3-D view• the facets are quadrilaterals, each a constant color, outlined
with black mesh lineswith black mesh lines. The shading command allows you to eliminate the mesh lines (shading flat) or to select interpolated shading
th f t ( )across the facet (shading interp).
• Lighting can add more realism.
mesh / surf
h( ) d i f h ith l• mesh(X,Y,Z) draws a wireframe mesh with color determined by Z, so color is proportional to surface h i htheight.
• surf(X,Y,Z) draws a 3-D shaded surface plot
Graphics3D_8
meshc / meshz
• meshc adds a contour plot directly below the meshmesh– helps visualize the
contourscontours
– can locate the peaks and dipsand dips
• meshz: allows to emphasize the zero plane in the mesh plotp p
• Ex. plot3D_meshc.m
Graphics3D_9
waterfall
• variation on the mesh plot and can also be useful in some specialuseful in some special cases
Graphics3D_10
surfl / contour3
fl di l h d d f b d• surfl displays a shaded surface based on a combination of ambient, diffuse, and specular lighting
d lmodels. • surfc acts much like meshc with a contour plot drawn
below the surface• contour3 creates a three-dimensional contour plot of
a surface defined on a rectangular grid.
Graphics3D_11
exploring hidden line removalp g
Hidden lines:• Hidden lines:– ON: shows white inside mesh
OFF sho s transparent mesh– OFF: shows transparent mesh • Ex. plot3D_hidden[X Y Z] h (12)[X,Y,Z] = sphere(12);subplot(1,2,1);mesh(X,Y,Z), title(‘Opaque');hidden on;axis square off;subplot(1,2,2);subplot(1,2,2);mesh(X,Y,Z),title('Transparent');hidden off;hidden off;axis square off;
shadingg
I l i f d• Improves color representation of data
• Shading command must FOLLOW the surf command• shading faceted
– Default
– Constant colour for each patch of plot– Black mesh lines
• shading flat will eliminate the mesh and leave the facets colored with a constant color value
• shading interp interpolates color over each facetColor varies linearly and smoothly along segmenty y g g
Graphics3D_13
setting the viewpointg p
• You can change the orientation of the objectobject– Viewing direction: view(az,el) or
you can use the rotate3d button on the i t lb th fi i dview toolbar on the figure window menu
– Camera direction: this is best controlled from the camera toolbar on the figure window menu
• Matlab enables you to specify the viewpoint view target orientation andviewpoint, view target, orientation, and extent of the view displayed in a figure window. All thi b d ll• All this can be done manually, or you can use the view command to select a view direction and let Matlab automatically do the rest.
• viewpoint control is convenient, but limited Complete control of a 3-D
Graphics3D_14
limited. Complete control of a 3-D scene is provided by camera capabilities
viewpointp
i ( i h l i )view(azimuth, elevation)– Azimuth = horizontal rotation
– Elevation = vertical elevation
• Default 2D view is:– 0 azimuth and
– 90deg elevation
• Default 3D view is: – –37.5deg azimuth,
– 30deg elevation
• Azimuth is about the z-axis, counter-clockwise
Graphics3D_15
lightingg g
Fl t li h i d if l h f h• Flat lighting produces uniform color across each of the faces of the object. Select this method to view faceted bj tobjects.
• Gouraud lighting calculates the colors at the vertices and then interpolates colors across the faces. Select this method to view curved surfaces.
• Phong lighting interpolates the vertex normals across each face and calculates the reflectance at each pixel. Select this choice to view curved surfaces. Phong lighting generally produces better results than G d li hti b t t k l t dGouraud lighting, but takes longer to render.
• ex. plot3D_lighting.m
Graphics3D_16
saving your graphg y g p
• Figures can be saved in a matlab binary format as a .fig file. The File menu of the figure window can be used for this, or the "save as" command.
• The export menu option of the same File menu can be used to save in other binary formats also (.eps, .bmp, .tif, .jpg , .ai, .emf, .pbm, .pcx, .png, .ppm ).
Graphics3D_17
MATLABMATLABgraphics handlesg p
Handle Graphics
• Every Matlab graphic is built-up from various objectsEvery Matlab graphic is built up from various objects
• Each instance of an object is associated with a unique identifier (number): Handle.( )
• A way to customize generic plots. Manipulate the characteristics (called object properties) of an existing graphics object.
• Low-level graphic features.
GraphicsHandles_2
Handle Graphics
• Handle Graphics is a way of controlling very specificHandle Graphics is a way of controlling very specific elements of a graphic display, without affecting or changing other elements of a plot
• hierarchical system of graphical objects, with a unique number (=handle)
h hild i h it th ti f it teach child inherits the properties of its parent
• each object has its properties
• exampleh = plot(x,y)set (h ‘linewidth’ 3)set (h, linewidth , 3)
GraphicsHandles_3
Root
Figure
UimenuAxesUicontrol UimenuAxesUicontrol
LightTextSurfacePatchLineImage
• Root: computer screen; can have one or several Figure windows • Figure: window with a Matlab figure. All graphics objects will be contained in
a Figure window . Each Figure window can contain Axes, Uicontrol, Uimenu, Uiconte tmenUicontextmenu
• Axes: determins the position in the window. Each axes can contain other objects including line, surface, text etc.Line: line used to create 2D or 3D plots• Line: line used to create 2D or 3D plots
• Surface: 3D representation of Matrices• Text: text object
F l d di h fi li d bj
GraphicsHandles_4
• For most plots, understanding the root, figure, axes, line and text objects are all that is needed.
object handles
• each object has an unique handle = integer or real numbernumberHnd1 = figurethis command creates a new figure and gives the identification back in Hnd1– root: handle = 0
fi i t b– figure: integer number
– other graphic objects: real numbers
• functions to retrieve handles• functions to retrieve handles– gcf: get current figure handle
– gca: get current Axisg
– gco: get current Object handle (last object in the current figure that was touched)
Ti h dl i bl th t t t ith H• Tip: use handles variables that start with H
• example: handle_1.m
object properties• object property: value that determines the behavior of
an objectan object
• at creation time, the values are set to default values
U h dl ith th f ti• Use handles with the functions– get
t i f tiget informationformatvalue = get(handle);value get(handle);value = get(handle, ‘PropertyName’);
– setset informationformatset(handle, ‘PropertyName1’, value1, ….)
object properties
• Example root properties: get(0)Example root properties: get(0)
• Get an overview of the options: set(0,’Format’)
• findobj locates graphics objects and returns theirfindobj locates graphics objects and returns their handles
GraphicsHandles_7
examples
• Examples:Examples:– handle_2.m
– handle_3.m
– handle_4.m
– handle_5.m
h dl 6– handle_6.m
– select_object.m
GraphicsHandles_8
MATLABfperformance
Contents
fil• profiler
• timing
• techniques to improve the performance of your MATLAB program– vectorisation
– preallocation
– other tips & tricks
Performance_2
Profilingg
Wh i P fili ?• What is Profiling?– Identify which functions in your code consume the most time.
(performance bottlenecks 80/20 r le )(performance bottlenecks -80/20 rule-)
– Determine why you are calling them and look for ways to minimize their useminimize their use.
• Profiling uncovers performance problems solved byAvoiding unnecessary computation which can arise from– Avoiding unnecessary computation, which can arise from oversight.
– Changing your algorithm to avoid time-consuming functions.g g y g g
– Avoiding recomputation by storing results for future use.
– Spending most of the time on calls to built-in functions.p g
MATLAB Profiler
GUI for ie ing here the time is being spent in o r M code• GUI for viewing where the time is being spent in your M-code. • Usage:
– Select Desktop-> Profiler from the MATLAB desktop.Select Desktop Profiler from the MATLAB desktop.– Select Tools->Open Profiler from the menu in the MATLAB
Editor/Debugger.Select one or more statements in the Command History window right– Select one or more statements in the Command History window, right-click to view the context menu, and choose Profile Code.
– Enter profile viewer in the Command Window:
• Running the Profiler on MATLAB code generates the following:– Profile Summary Report presents statistics about the overall execution
of the function and provides summary statistics for each functionof the function and provides summary statistics for each function called.
– Profile Detail Report shows profiling results for a selected function that was called during profilingwas called during profiling.
Performance_4
Profiler Guidelines
S mmar report look for f nctions that sed a significant amo nt• Summary report: look for functions that used a significant amount of time or were called most frequently.
• View the detail report for those functions and look for the lines that puse the most time or are called most often. Keep a copy of your first detail report to use as a reference.
• Determine whether there are changes you can make to the lines• Determine whether there are changes you can make to the lines most called or the most time-consuming lines to improve performance
• Run the Profiler again and compare the results to the original report.
• Repeat this process to continue improving the performance• Repeat this process to continue improving the performance.
• Total Time — The total time spent in a function, including all child functions called, in seconds. ,
• Self Time — The total time spent in a function, not including time for any child functions called, in seconds.
Performance_5
m file profilerp
l• example: – mandelbrot.m
mandelbrot improved m– mandelbrot_improved.m
• Advice– Premature optimization can increase code complexity– Premature optimization can increase code complexity
unnecessarily without providing a real gain in performance.– Do not forget to comment: optimized code can be cryptic– Your first implementation should be as simple as possible.
Then, if speed is an issue, use profiling to identify bottlenecks.
Performance_6
Timingg
h h i f i• use the stopwatch timer functions to:– get an idea of how long your program (or a portion of it) takes to
r nrun
– to compare the speed of different implementations of a program
MATLAB ti i f ti• MATLAB timing functions:– tic toc
ti– cputime
– etime
Performance_7
Timingg
TIC/TOC• TIC/TOC– TIC: starts the stopwatchTOC: stops the stopwatch and displays the elapsed time– TOC: stops the stopwatch and displays the elapsed time
– TIC/TOC functions measure "wall clock" time (other processesrunning on the computer are also taken into account)
• CPUTIME measures the actual CPU time spent on the process.
• ETIME calculates the time elapsed between 2 time vectors
• example– timing_ex_1.m– timing_ex_2.m
Performance_8
Vectorisation
• Vectorization means converting for and while loopsVectorization means converting for and while loops to equivalent vector or matrix operations.
t d t i th b i d t t d i• vectors and matrices are the basic data types used in MATLAB , try to exploit it.
• use vector and/or matrices instead of for or while loopsloops
• examplei 0 ffi i ti=0; more efficientfor t=0:0.1:10 t=0:0.1:10;
i i+1; y sin(t);i=i+1; y=sin(t);y(i)=sin(t);
endPerformance_9
end
Vectorisation
• Using the for loop in MATLAB is relatively expensive It• Using the for loop in MATLAB is relatively expensive. It is much more efficient to perform the same task using the vector method. example:for j=1:n
for i=1:mfor i=1:m A(i,j) = B(i,j) + C(i,j);
end dend
can be more compactly and efficiently represented by the vector method as follows:the vector method as follows:A = B + C;
• For sufficiently large matrix operations, this method is i i fsuperior in performance
• driver_minDistance.m
Performance_10
Array Operationsy p
A O ti M t i O tiArray Operations vs. Matrix Operations• Use array operations to replace loops that perform only
simple arithmetic on scalar datasimple arithmetic on scalar data.for n = 1:100V( ) 1/12* i*(D( )ˆ2)*H( )V(n) = 1/12*pi*(D(n)ˆ2)*H(n);
endPerform the vectorized calculationV = 1/12*pi*(D.ˆ2).*H;• difference is the use of the .* and ./ operators. • differentiate array operators (element-by-element
operators) from the matrix operators (linear algebra operators), * and /.
Performance_11
Logical Array Indexingg y g
• logical array indexing: the index parameter is a logical t i th t i th i d t imatrix that is the same size as an array and contains
only 0’s and 1’s. • The array elements selected have a ’1’ in the• The array elements selected have a 1 in the
corresponding position of the logical indexing matrix.D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14];D >= 0ans=0 1 1 1 0 1 10 1 1 1 0 1 1
• select the subset of V for which the corresponding elements of D are nonnegative.gVgood = V(D>=0);
• vectorized Boolean operators, any and all, which f B l AND d OR f ti tperform Boolean AND and OR functions over a vector. if all(D < 0)
warning(’All values of diameter are negative.’);g( g );return;
end
Vectorisation
• another example: delete second column of B B(: logical([1 0 1]))B(:,logical([1 0 1]))
Performance_13
Preallocating Arraysg y
• for and while loops that incrementally increase the size• for and while loops that incrementally increase the size of a data structure each time through the loop can adversely affect performance and memory use.y p y
• Advice: improve on code execution time by preallocating the maximum amount of space that would be required for the array ahead of timebe required for the array ahead of time.
x = 0;for k = 2:1000
x(k) = x(k-1) + 5;end
Preallocate a 1-by-1000 block of memory for x initialized to y yzero.
x = zeros(1, 1000);for k = 2:1000for k 2:1000
x(k) = x(k-1) + 5;end
Performance_14
Preallocation
• Avoids overhead of dynamic resizingidea: allocate memoryidea: allocate memory, in order to eliminate the search for continuoussearch for continuous memory blocks
• Reduces memory fragmentationg
• Use array appropriate preallocationpreallocation
• example: alloc_ex_1.m
Performance_15
Preallocation
• Preallocating a non-double Matrixguint8(zeros(100))
thi t t t ill fi t t f ll t i f• this statement will first create a full matrix of doubles and then convert it to uint8, this takes time and uses memory unnecessarily
• using repmat you create only 1 doubleusing repmat, you create only 1 double, reducing memory needs
( i 8(0) 100 100)repmat(uint8(0), 100, 100)
• Use repmat to enlarge arraysp g yB = repmat(A,m,n) creates a large matrix B consisting of an m-by-n tiling of copies of A
Performance_16
consisting of an m-by-n tiling of copies of A.
Scripts & functionsp
U f ti t i tUse functions, not scripts
• Scripts are always read and executed one line at a time (interpreted). No matter how many times
• you execute the same script, MATLAB must spend time parsing your syntax. By contrast, functions are effectively parsed into memory when called for the first time or modified. Subsequent invocations skip the interpretation step.
• As a rule of thumb, scripts should be called only from the command line, and they should themselves call only functions, not other scripts.
Performance_17
Memory Usagey g
MATLAB functions available for memory• MATLAB functions available for memory management:
clear: clear all variables from the workspace– clear: clear all variables from the workspace, liberating memory
– pack: extended MATLAB-sessions can fragmentpack: extended MATLAB sessions can fragment memory. Fragmented memory usually means enough meory but not in continuous blocks. MATLAB Out of memory can be cured with pack :MATLAB Out of memory can be cured with pack : free up memory without deleting variablessaves existing variables to disk and reloads then gcontinguously
– quit: stop– save: fastest way to save data– load: fastest way to read data
h h h h b ll t d– whos: shows how much memory has been allocated for variables in workspace
Ways to Conserve Memoryy y
Advice:Advice:
• clear unused variables from memory
• large amounts of data: consider writing data to disk periodically, after saving clear the varibles p y gfrom memory
• convert full matrices into sparse: matrices with• convert full matrices into sparse: matrices with values that a mostly 0, are best stored in sparse f tformat
• preallocate as much matrices at the beginning p g gof your program
• use pack to consolidate fragmented memoryPerformance_19
• use pack to consolidate fragmented memory
Memory Limitsy
i l li i f 2^31 l i MATLAB• internal limit of 2^31 elements per array in MATLAB (regardless of platform)
• A 2^31 element double array would require 16 GB of space (is possible on a 64bit architecture)
• on a Windows platform, you can see the memory allocation along with the largest contiguous block of memory available with the following methods. – feature('memstats')
– m = feature('memstats') return a value containing the number of bytes in the largest available memory block
Performance_20
More Hints
l d d f t th Fil I/O F ti• load and save are faster than File I/O Functions
• Avoid running in debug mode
• Avoid command echoing
• Avoid large background processesAvoid large background processes
Performance_21
Summaryy
fil• profiler– use it also to understand a lengthy program (debugging tool)
– points at the time-consuming code
• timing– tic toc
– cputime
• techniques to improve the performance of your MATLAB program– vectorisation: try to use it as much as possible
– preallocation
– functions vs scripts
– ...
Performance_22
References
C d V i i G id• Code Vectorization Guide
http://www.mathworks.com/support/tech-notes/1100/1109.html
• Memory management
http://www.mathworks.com/support/tech-notes/1100/1106.html
Performance_23
MATLABMATLABGUI using GUIDEg
GUI
• GUI: graphical user interfaceGUI: graphical user interface– provides the user with a familiar environment,
makes it user friendly, makes the use of a program easier
– works with intuitive control elements (list box, pushbutton )pushbutton, …)
– interactive demo of your ideas/data/algorithms– someone else needs to run your codesomeone else needs to run your code– impress your colleagues, friends– just for the funjust for the fun
• hard(er) to program: be prepared for mouse clicks and keyboard input at any time on any c c s a d eyboa d put at a y t e o a yGUI element. event driven programming
game example
• Tic Tac Toe game
• author: Victoria Brumberg(Mathworks)
• file: tictactoe.m
GUI_3
scientific example
• Bus Suspension example (Carnegie Mellon)Bus Suspension example (Carnegie Mellon)
• File: busGUI.m
GUI_4
basic steps in the GUI creation
design-phaseg p• determine the elements needed and their function.
draw the layout on paper.lay out phase• use guide the build the lay-out.
i hprogramming phase• use the property inspector to tag each element
save the figure on file: 2 files are created:• save the figure on file: 2 files are created:– fig-file: GUI– m-file: code to load the figure, together with the callbacks g , g
frame
• write the code used in each callback.
GUI_5
MATLAB GUIDE
creating a GUI, the basic steps
GUI_6
GUI: basic elements
• components: each element is a graphical componentcomponents: each element is a graphical component– graphical controls: push button, list, editbox, …(uicontrol)
– static elements: frames and text string (uicontrol)
– menu (uimenu, uicontextmenu)
– axes (axes)
fi t h t b l d i t fi• figures: components have to be placed into a figure
• callback: if the user does something, an action has to followfollow. i.e. some code has to be executed in respons to an eventevent.
GUI_7
GUIDE
• GUIDE simplifies the process of creating GUIs byGUIDE simplifies the process of creating GUIs by automatically generating the GUI m-file.
• GUIDE generates:g– callbacks: a callback is generated for each component that
requires it. The code itself has to be completed by the user
i f ti f t k b f th GUI b– opening function: performs tasks before the GUI becomes visible
– output function: outputs variables to the command line, if p p ,necessary
GUI_8
GUIDE templates
• GUIDE provides several templatesGUIDE provides several templates
• templates are fully functional and callbacks are programmed, view the code and modify itp g , y
GUI_9
GUIDE
• GUIDE: GUIDevelopmentDevelopment Environment
• lay-out of the GUI oncelay out of the GUI once placed, the properties can be changed.
• call: guidein command window
GUI_10
GUI: .fig & .m
GUIDE stores a GUI in 2 files:GUIDE stores a GUI in 2 files:
• FIG-file: a complete description of the GUI figure layout and the components of the GUI: push buttons, menus,p p , ,axes, etc.edit with guide
• M-file: contains the code that controls the GUI, including the callbacks for its components.edit with the matlab editoredit with the matlab editor.
GUI_11
gui_1: step 1
example gui 1: count the clicksexample gui_1: count the clicks
1. determine the lay out of the screen:- text field to display the counterp y
- counter button
counter
Push button
GUI_12
gui_1: step 2 (1)
2. use guide to set up the gui2. use guide to set up the gui
select the Blank GUIselect the Blank GUI
GUI_13
gui_1: step 2 (2)
set the dimension of the figureset the dimension of the figure
• open the property inspector (using the menu or right mouse click))
• set the Units
• change the dimensions if needed in Positiong
GUI_14
gui_1: step 2 (3)
align the objectsalign the objects
• select the objects (click and hold the ctrl-key)
• select the option align objects from the tools menuselect the option align objects from the tools menu
• try to align the objects horizontally and vertically
GUI_15
gui_1: step 2 (4)
GUI_16
gui_1: step 3
3. inspect the properties of each element and initialize3. inspect the properties of each element and initialize when necessary
change the label (String)
change color (Color)g ( )
change letter type (Font..)
......
remember the Tag!remember the Tag!
GUI_17
gui_1: step 4
4. save the lay out: 2 files will be saved4. save the lay out: 2 files will be saved
gui_1.fig
gui 1 mgui_1.m
GUI_18
gui_1: step 5
5. edit gui 1.m to implement the callback routines5. edit gui_1.m to implement the callback routines
basic structure is generated by matlabbasic structure is generated by matlab
the callback routines
have to be completedhave to be completed
use a counter touse a counter to
count the clicks
GUI_19
GUIDE Tools
• components
• Layout
• M-file
GUI_20
gui components
• Push Buttons (psh )(p _)• Toggle Buttons (tog_)• Radio Buttons (rad_)• Check Boxes (chk_)• Edit Text (edt_)• Static Text (stt_)• Sliders (sli_)• Frames (frm_)• List Boxes (lst_)
P U M ( )• Pop-Up Menus (pop_)• Axes (axe_)• Figures (fig )
GUI_21
• Figures (fig_)
uicontrol: push button
• Push buttons generate an action when clicked. WhenPush buttons generate an action when clicked. When you click the mouse on a push button, it appears depressed; when you release the mouse, the button appears raised; and its callback executes.
• Properties to Set:– String: string displayed on the push button.
– Tag: GUIDE uses the Tag property to name the callback subfunction in the GUI M-file give it a descriptive namesubfunction in the GUI M file, give it a descriptive name.
• Callback: clicks on the push button, the callback executes. Push p ,buttons do not return a value or maintain a state.
GUI_22
uicontrol: toggle button
• Toggle buttons generate an action and indicate a gg gbinary state (e.g., on or off). Clicking on a toggle button, it appears depressed and remains depressed until you release the mouse button at which point the callbackrelease the mouse button, at which point the callback executes. Clicking again returns the toggle button to the raised state and again executes its callback.
• Callback:the routine needs to query the toggle button to determine what state it is indetermine what state it is in. MATLAB sets the Value propertydepressed => Max (1 by default) not depressed => Min (0 by default).
GUI_23
uicontrol: radio button
• Radio buttons: similar to check boxes, but are ,intended to be mutually exclusive within a group of related radio buttons (i.e., only one button is in a selected state at any given time)selected state at any given time).
• Callback:Radio buttons have two states - selected and not selected. Query and set the state of a radio button through its Value property:Value property: Value = Max, button is selected (1 by default) Value = Min, button is not selected (0 by default)
GUI_24
uicontrol: check box
• Check boxes: generate an action when checked and indicate their gstate as checked or not checked. Check boxes are useful when providing the user with a number of independent choices that set a modemode
• CallbackThe Value property indicates the state of the check box by taking
th l f th M Mi ton the value of the Max or Min property Value = Max, box is checked. Value = Min, box is not checked. function checkbox1_Callback(hObject, eventdata, handles)if (get(hObject,'Value') == get(hObject,'Max'))
% then checkbox is checked-take appropriate action
else
% checkbox is not checked-take appropriate action
end
GUI_25
uicontrol: Edit Text
• Edit text: fields that enable users to enter or modify textEdit text: fields that enable users to enter or modify text strings. Use edit text when you want text as input. The String property contains the text entered by the user.
• Callback:bt i th t i t d b th i th St iobtain the string typed by the user, using the String
property in the callback.
function edittext1_Callback(hObject, eventdata, handles)
t i t(hObj t ' t i ')user_string = get(hObject,'string');% proceed with callback...
GUI_26
uicontrol: Static Text
• Static text: controls display lines of text.Static text: controls display lines of text. Static text is typically used to label other controls, provide directions to the user, or indicate values associated with a slider. Users cannot change static text interactively
C llb k• Callback:there is no way to invoke the callback routine associated with itassociated with it.
GUI_27
uicontrol: slider
• Slider: accept numeric input within a specific range by p p p g yenabling the user to move a sliding bar. The location of the bar indicates a numeric value. C llb k• Callback:– slider callback is executed when the user releases the mouse
button. – 4 properties control the range and step size of the slider:
• Value contains the current value of the slider. • Max defines the maximum slider valueMax defines the maximum slider value. • Min defines the minimum slider value. • SliderStep specifies the size of a slider step with respect to the
rangerange.
– query it in the slider's callback to obtain the value set by the user. slider value = get(handles.slider1,'Value');
GUI_28
slider_value get(handles.slider1, Value );
uicontrol: frames
• Frames: boxes that enclose regions of a figure window.Frames: boxes that enclose regions of a figure window. Frames can make a user interface easier to understand by visually grouping related controls.
• Callback:Frames have no callback routines associated with them
d l i t l ithi fand only uicontrols can appear within frames.
GUI_29
uicontrol: list box
• List boxes: a list of items, enable users to select oneList boxes: a list of items, enable users to select one or more items. String property contains the list of strings displayed in the list box. The first item in the list has an index of 1. Value property contains the index into the list of strings that corresponds to the selected itemthat corresponds to the selected item.
• Callback:MATLAB evaluates the list box's callback after theMATLAB evaluates the list box s callback after the mouse button is released or a keypress event (including arrow keys) that changes the Value property In these y ) g p p ysituations, you need to add another component, such as a Done button (push button) and program its
llb k ti t th li t b l tGUI_30
callback routine to query the list box Value property
uicontrol: Pop-up menu
• Pop-up menus: open to display a list ofPop up menus: open to display a list of choices when users click the arrow. The String property contains the list of string displayed in the pop-up menu.
• Callback:the popup menu callback can work by checking only the index of the item selected (contained in th l t ) thi i d t t ithe Value property) or use this index to retrieve the value of the string
function popupmenu1 Callback(hObject, eventdata, handles)function popupmenu1_Callback(hObject, eventdata, handles)val = get(hObject,'Value');switch valcase 1% h l d h fi i% The user selected the first itemcase 2% The user selected the second item% etc.
uicontrol: axes
• Axes: enable your GUI to display graphics (e.g., graphs y p y g p ( g , g pand images). Like all graphics objects, axes have properties that you can set to control many aspects of its behavior and appearanceits behavior and appearance.
• Callback:Axes are not uicontrol objects, but can be programmed j , p gto execute a callback when users click a mouse button in the axes. Use the axes ButtonDownFcn property to define the callbackdefine the callback.
GUI_32
layout: aligning
• Aligning Groups of Components: enables theAligning Groups of Components: enables thepositioning of objects with respect to each other.
• The specified alignment operations apply to all p g p pp ycomponents that are selected when you press the Apply button.
• 2 types of alignment operations: – Align: align all selected
components to a singlecomponents to a single reference line.
– Distribute: space all selected components uniformly with respect to each other.
GUI_33
layout: grid and ruler
• Grids and Rulers:Grids and Rulers:Grid lines are spaced at 50-pixel intervals (default), other values ranging from 10 to 200 pixels. You can optionally enable snap-to-grid, which causes any object that is moved or resized to within 9 pixels of a grid line to jump to that linea grid line to jump to that line.
GUI_34
GUI m-file: a closer look
Part1: Calling the function without parameters will start the GUI. Passing the name of a callback function will execute this functionPassing the name of a callback function will execute this function
function varargout = calc_day_1(varargin)% CALC_DAY_1 M-file for calc_day_1.fig% CALC_DAY_1, by itself, creates a new CALC_DAY_1 or raises the existing% singleton*% singleton*.% ….
% Begin initialization code - DO NOT EDITgui Singleton = 1;gui_Singleton 1;gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...'gui_OpeningFcn', @calc_day_1_OpeningFcn, ...'gui_OutputFcn', @calc_day_1_OutputFcn, ...'gui_LayoutFcn', [] , ...'gui_Callback', []);
if nargin & isstr(varargin{1})gui_State.gui_Callback = str2func(varargin{1});
end
if nargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
elseelsegui_mainfcn(gui_State, varargin{:});
end% End initialization code - DO NOT EDIT
GUI m-file: a closer look
Part2: used for initialization. The structure handles can be extended in this phase.
% --- Executes just before calc_day_1 is made visible.function calc day 1 OpeningFcn(hObject, eventdata, handles,function calc_day_1_OpeningFcn(hObject, eventdata, handles,
varargin)% This function has no output args, see OutputFcn.% hObject handle to figure% eventdata reserved - to be defined in a future version of
MATLAB% handles structure with handles and user data (see GUIDATA)% varargin command line arguments to calc day 1 (see VARARGIN)% varargin command line arguments to calc_day_1 (see VARARGIN)handles.daylist = {‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, …
‘Thursday’, ‘Friday’, ‘Saturday’};y y yset (handles.edt_day, ‘String’, ’27’);% Choose default command line output for calc_day_1handles.output = hObject;
GUI_36% Update handles structureguidata(hObject, handles);
GUI m-file: a closer look
Part3: callback functionsPart3: callback functions• Each GUI object has a _Callback function: activated
when the object is touched (click or input)j ( p )
• This function is added to the m-file when a new object is added in the figure. The name is Tagname_…. It is important to keep track of the different tags!
GUI_37
Useful information
• Mathworks websiteMathworks website
• http://www.blinkdagger.com/matlab
GUI_38
MATLABtilitisome utilities
Publish tool
C ll l f l if t t h• Cells are also useful if you want to share your results by publishing your work in a
t ti f tpresentation format: – an HTML document. – word document– powerpoint document– …
• Not only can the code itself be presented, butNot only can the code itself be presented, but also commentary on the code and results from running the file can be displayed.running the file can be displayed.
• demo_publish_sine_wave –publish(‘file name’ ‘doc’)
utilities_2
publish( file name , doc )
Publish to HTML
Overall process of publishing to HTML:Overall process of publishing to HTML:– In the Matlab Editor/Debugger, enable cell mode.
Select Cell -> Enable Cell ModeSelect Cell -> Enable Cell Mode. – Define the boundaries of the cells in an m-file script
using cell features. gA cell is just a defined contiguous section of code.A cell can be created by positioning the cursor just above the line where the cell is to begin and thenabove the line where the cell is to begin and then selecting Cell -> Insert Cell Divider.
– two percent signs (%%) indicate the start of the cell.p g (%%)– cell title, can be appended by entering a blank space
followed by a text string on the same line.– All subsequent lines of code will belong to the cell
until another cell start (%%) occurs. Select File > Publish To HTML
utilities_3
– Select File -> Publish To HTML
Markupp
U h T M k l• Use the Text Markup tool
utilities_4
Markup: Structural Elementsp
• Overall document heading• Overall document heading– %% TITLE– Add any overall comments about the file in the lines following Add any overall comments about the file in the lines following
this title. If you want the first title to appear as the overall document title, do not add code after the first title and before the next cell (the line starting with %%)( g )
• Section title – Position the cursor at the start of a cell, select this menu item,
and in the resulting text replace TITLE with the cell title youand in the resulting text, replace TITLE with the cell title you want.
• Descriptive textp– Position the cursor where you want to add a formatted
comment, select this menu item, and replace the resulting DESCRIPTIVE TEXT with your comment.DESCRIPTIVE TEXT with your comment.
– descriptive text must appear before the first line of code in a cell.
utilities_5
Markup: Block Stylesp y
• Indented text• Indented text– Preformatted Text– Select this menu item.
• Bullets– select this menu item. – The * at the start of a block distinguishes it as a bulleted list.g% * ITEM1% * ITEM2
• TeX Equation• TeX Equation– select this menu item. – The equation is surrounded with $$$$ ^{\ i i} 1 0$$$$e^{\pi i} + 1 = 0$$
• Graphic– Enclose the name of the graphic file within a double set of angle g p g
brackets (<<>>).%% Graphics Area% <<surfpeaks.jpg>>p jpg
• HTML– Use the HTML tags <html> and </html> to use HTML formatting.
Markup: Inline elementsp
• Bold text• Bold text– Select the text within a comment that you want to appear in bold and then select this menu
item.– Enclosed between *% *BOLD TEXT*
• Italic text– Select this menu item.– Enclosed betweenEnclosed between _% _ITALIC TEXT_
• Monospaced text– Select the text within a comment that you want to appear in a monospaced font and then
l t thi itselect this menu item. – Enclosed between |% |MONOSPACED TEXT|
• Links for HTML outputLinks for HTML output– If the URL is the only information on the line, enter comment text that consists of a valid
Internet address.– % http://www. mathworks.com
• Inline links• Inline links– Enclose an Internet address within a pair of angle brackets < >.– % For further information contact The MathWorks at <http://www.mathworks.com>.
• Inline links with link textInline links with link text– Within a pair of angle brackets < >, enclose an Internet address, followed by a space, and
then the link text.– % For information contact <http://www.mathworks.com The MathWorks>.
Shortcut Utilityy• A Matlab shortcut is an easy way to
run a group of Matlab commands thatrun a group of Matlab commands that are used regularly (cfr. macro )
• Shortcuts can be created from the Start -> Shortcuts menu
• From the Start button, select Shortcuts -> New Shortcut. The Shortcut Editor dialog box appears.
• Create the shortcut using these steps:– Provide a shortcut name in the Label
field to identify it P t th f d t t t– Put the group of command statements in the Callback field.
• keyboard typing, • copy and pastepy p
– Assign a category– Click Save.
• examplepclear;format long e;disp('Memory has been cleared');
Shortcut Utilityy
• alternative to creating and running shortcuts: use the• alternative to creating and running shortcuts: use the Shortcuts toolbar. To show or hide the shortcuts toolbar, toggle the , ggDesktop -> Shortcuts Toolbar menu item.
• create and run shortcuts via the desktop Shortcutstoolbar go through a similar procedure:toolbar, go through a similar procedure:– Select statements from the Command History window, the
Command Window, or an m-file. – Drag the selected group of commands to the desktop
Shortcuts toolbar and the Shortcut Editor dialog box will appear.ppCategory field needs to be retained as Toolbar Shortcuts so that the shortcut will appear on the toolbar.
– Choose a Label, select an Icon, and click the Save button. TheChoose a Label, select an Icon, and click the Save button. The shortcut icon and label will then appear on the toolbar.
utilities_9
Directory reportsy p
• Accessed from the current directory browser
• M-lint code checker:displays potential problems in your code as well as opportunities for improvementspp p
utilities_10
Directory reportsy p
TODO/FIXME Report• TODO/FIXME ReportSearches the current directory for keywords (TODO, FIXME, …) and displays the files that contains these keywords
• HELP ReportSummarizes help information in your m-files
• Contents Report• Contents Report displays information about the integrity of the Contents.m file for the directory.
• Dependency ReportShows dependencies among m-files in a directory
• Coverage Report• Coverage ReportRun the Coverage Report after you run the Profiler to identify how much of a file ran when it was profiled. – example, when you have an if statement in your code, that section
might not run during profiling, depending on conditions.
utilities_11
MATLABMATLABtraveling salesperson g pproblem
Problem
• Instance: n vertices (cities), distance between every
1 24
3distance between every pair of vertices
• Question: Find shortest 3 4
52 3
21 2
4Question: Find shortest (simple) cycle that visits every city
3 42 1 2
52 3
23 42
2
1 24
52 3
3 4
5
2
22
TSP_2
11xkcd.com/399/
Applications
• Collection and delivery problemsCollection and delivery problems
• Robotics
• Board drillingBoard drilling
• …
TSP_3
NP-complete
• Through 50 cities go 49!/2 toursThrough 50 cities go 49!/2 tours– 49!/2 = 3.041 10^62
• Supercomputer: 10^9 pathways/secondp p p y– assume 3.10^7 seconds/year
– 3.10^7.10^9 = 3.10^16 pathways evaluated/year
• in 5x10^9 years 10^24 pathways evaluated
TSP_4
Heuristics and approximations
• Two typesTwo types– Construction heuristics
• A tour is built from nothing
– Improvement heuristics• Start with `some’ tour, and continue to change it into a better one as long
as possible
TSP_5
Heuristic: Nearest Neighbour
• Start at some vertex s; v=s;Start at some vertex s; v s;
• While not all vertices visited– Select closest unvisited neighbour w of vg
– Go from v to w;
– v=w
• Go from v to s.
TSP_6
Heuristic: Farthest Neighbour
• Start at some vertex s; v=s;Start at some vertex s; v s;
• While not all vertices visited– Select farthest unvisited neighbour w of vg
– Go from v to w;
– v=w
• Go from v to s.
TSP_7
Improvement heuristics
• Start with a tour (e.g., from heuristic) and improve it ( g , ) pstepwise– 2-Opt
3 O t– 3-Opt– K-Opt– Lin-Kernighang– Iterated LK– Simulated annealing, …
TSP_8
Programming?
• What is the input?What is the input?– File with coordinates of the cities
– File with the distances?
• What is the output?– Length of a tour,
i h f thusing each of theheuristics
– Tour
– A plot would be nice
TSP_9
Programming?
• What are the solution methods?What are the solution methods?– Enumeration
– Nearest neighbour
– Farthest neighbour
– Random
St t h f th th d t• Structure: program each of the methods as a separate function
? Are there built in matlab functions that will make life• ? Are there built-in matlab functions that will make life easy?– Permutations (check in help for permutation)Permutations (check in help for permutation)
TSP_10
Programming?
• Input:Input:– Read file
– Know the structure of the file
• Additional information needed? – Calculate the distance between the cities (beforehand? Store it
i t d f l l ti it d i )instead of calculating it over and over again)
– The length of each route has to be calculated
TSP_11
MATLABiimages
Contents
Th b i t ti f i• The basic representation of images
• How to read, display, and write JPEG image files
Some basic operations on images• Some basic operations on images
• Some advanced image processing techniques
Images_2
Digital Image Representationg g p
A i b d fi d t di i l• An image may be defined as a two-dimensional function, f(x, y):– x and y are spatial coordinates, and– f is the intensity of the image at (x, y) point.
• digital image : x, y and the amplitude values of f are all finite, discrete quantities., q
• Digital images are discrete functions that correspond to the average scene luminancecorrespond to the average scene luminanceas perceived by the camera over a period of timeover a period of time
– Discrete spatially
Images_3– Discrete quantization
Digital Image Structureg g
• A digital image is a 2D array ofA digital image is a 2D array of pixels, where a pixel is the smallest addressable element
pixelsmallest addressable element of the array.
• The depth of a pixel in bits p pdetermines how many colors can be displayed.
rowp y
• Every pixel is a matrix element
• All the operators in MATLABAll the operators in MATLAB defined on matrices can be used on images: + - * / ^
columnused on images: +, , , /, , sqrt, sin, cos etc.page origin (top left)
Images_4
Digital Image Structureg g
I b id d t i hImages may be considered as matrices whose elements are the pixel values:
• black and white images or binary images, containing 1 for white and 0 for black.g
• grayscale images or intensity images, containing numbers in the range of 0 to 255 orcontaining numbers in the range of 0 to 255 or 0 to 1.
• colored image represented as RGB Image or indexed image.de ed age
– RGB images: m*n*3
Images_5– Indexed images: m*n and c*3 color map
Images_6
Binary imagey g
d t t idata matrix • M*N• 1 bit/pixel• B&W images• B&W images• only 2 values (binary image is a logical array of
0 d 1 )0s and 1s): – 0/1– on/off– true/false
• Often used as mask for selecting regions of interest (ROI) from other images
Images_7
( ) g
Binary imagey g
• binary image 01 m:binary_image_01.m: generate a BW picture
• binary image 02.m: readbinary_image_02.m: read a BW picture and show it onto the screen
Images_8
Grayscale / Intensityy y
data matrixdata matrix• M*N• grayscale imagesgrayscale images• The matrix can be of:
– class double - range [0 1]class double range [0,1] – class uint8 - range is [0,255].
• Value = 0: BLACKValue 0: BLACK (no illumination / energy)
• Value = 255: WHITE (max. illumination / energy)
• demo_image_3D
Images_9
True color
d t M t idata Matrix• M * N * 3 RGB(m,n,i)
f• An individual pixel color is defined by thecorresponding values in the three color pagesA RGB b f l d bl i hi h it• An RGB array can be of class double, in which case it contains values in the range [0,1], or of class uint8, in which case the data range is [0 255]which case the data range is [0,255].
• demo_01_imread_rgb
Images_10
True color
Color images represented by
3D Arrays
Images_11
True Color
Images_12
Index imagesg
• Data Matrix (X) • map( )– M * N– Each value points to a
specific color vector in the
map
R G Bspecific color vector in thecolormap
• An efficient way of storing colour image information is as an
1 1 0 0
2 0 1 0
3 0 0 1
image information is as an indexed image
• Colormap Matrix (map) • data matrix
4 1 1 0
5 1 1 1
6 0 0 0p ( p)– C * 3 matrix– 3 cols: Red, Blue, Green
C C l t [0 1] 1 2 3 4 5– C rows: Color vector [0:1]– Also called a color lookup
table (LUT)
1 2 3 4 5
6 4 6 1 2
3 1 3 5 4
• [X, map] = image file• demo_01_imread_indexed
d i d diImages_13
demo_indexedimage
Colormap (8 bits/pixel)p ( p )
image look-up table
Images_14
Importing & exporting imagesp g p g g
i fi f t fil i f ti• imfinfo - returns file information
• imread - reads image– Intensity, RGB, & Binary Images:
X=imread(‘file.fmt’)
I d d I– Indexed Images:[X,map]=imread(‘file.fmt’)
• imwrite writes image• imwrite - writes image
Images_15
Matlab function imfinfo
• info = imfinfo(filename fmt) returns a structure• info = imfinfo(filename,fmt) returns a structure • set of fields depends on the individual file and its format.
first 9 fields are always the same. • common fields:
– FieldValueFilename: string containing the name of the file; – FileModDate: string containing the date when the file was last modifiedg g– FileSize: integer indicating the size of the file in bytes– Format: string containing the file format, as specified by fmt; – FormatVersion: string or number describing the version of the formatFormatVersion: string or number describing the version of the format– Width: integer indicating the width of the image in pixels– Height: integer indicating the height of the image in pixels
BitDepth: integer indicating the number of bits per pixel– BitDepth: integer indicating the number of bits per pixel– ColorTypeA string indicating the type of image;
• 'truecolor' for a true color RGB image, ' l ' f l i t it i• 'grayscale' for a grayscale intensity image, or
• 'indexed' for an indexed image
• demo_imfinfo
Images_16
_
Matlab function imread
• Reads an imageReads an image• Validates the graphic format• Stores it in an arrayStores it in an array• A = imread(filename) reads a grayscale or true color
image named filename into A. – If the file contains a grayscale intensity image, A is a two-
dimensional array. If the file contains a true color (RGB) image, A is a three-( ) gdimensional (m*n*3) array.
• [X,map] = imread(filename,fmt) reads the indexed image in filename into X and its associatedindexed image in filename into X and its associated colormap into map. The colormap values are rescaled to the range [0,1]
• Demo_01_imread...
Images_17
Common Image Formatsg
Format Recognized Name Description Lossy? Extensions
TIFF Tagged Image File Format
S pport binar gra scale tr ecolor
No .tif, .tiff
Support binary, grayscale, truecolor and indexed images
JPEG Joint Photographic Experts Group Yes .jpg, .jpeg
GIF Graphics Interchange Format† Yes .gif
PNG Portable Network Graphics Yes .png
BMP Windows Bitmap No .bmpp p
XWD X Windows Dump .xwd
†GIF is supported by imread but not by imwrite.
Images_18
Matlab function imwrite
i it (A fil ) it th i i A• imwrite(A,filename) writes the image in Ato filename in the format specified by the file
t i ( j )extension (e.g., .jpg). A can be either a grayscale image (M*N) or a t l i (M*N*3)truecolor image (M*N*3).
• imwrite(X,map,filename) writes the pindexed image in X and its associated colormap map to filename in the format specified by the p p yfile extension.
• Standard image formatStandard image format (bmp,tiff,jpeg,png,hdf,pcx,xwd)
• demo imwriteImages_19
• demo_imwrite
Image displayg p y
• image function: primary function to use in Matlabg p y• MATLAB also includes the imagesc function, which is
similar to image but which automatically scales the input datadata.
• Image Processing Toolbox includes an additional display routine imshowroutine, imshow.automatically sets various Handle Graphics properties and attributes of the image to optimize the display.
Images_20
Matlab function imageg
i (C) displays matrix C as an image• image(C) displays matrix C as an image. Each element of C specifies the color of a rectilinear patch in the image C can be arectilinear patch in the image. C can be a matrix of dimension M*N or M*N*3, and can contain double, uint8, or uint16 data.contain double, uint8, or uint16 data.
• When C is a 2-dimensional M*N matrix, the elements of C are used as indices into theelements of C are used as indices into the current COLORMAP to determine the color.
• demo 02 image displaydemo_02_image_display• Better to use a more convenient command that
does most of the color mapping:does most of the color mapping:imshow is recommended by MATLAB for image processing
Images_21
g p g
function imshow
i h (i ) di l th i i hi h b• imshow(im) displays the image im, which may be truecolor, grayscale or binary.imshow(I [low high]) displays I as a grayscale• imshow(I,[low high]) displays I as a grayscale intensity image, specifying the data range for I. The value low displays as blackThe value low displays as black, the value high displays as white values in between display as intermediate shades of p ygray.
• imshow(X,map) displays the indexed image X with the colormap map.
• imshow filename displays the image stored in the hi fil fil i h ll i d t d thgraphics file filename. imshow calls imread to read the
image from the file, but the image data is not stored in the MATLAB workspace
Images_22
the MATLAB workspace.
colormapp
• A colormap is simply a 3 column matrix whose length (# of rows) is equal to the number of g ( )colors it defines.
• You can see the color scale by looking at a• You can see the color scale by looking at a colorbar: open a new figure window (type "fi ") th t " l b " d l"figure") then type "colorbar", and a color definition scale bar will appear on your map.
• demo_colormap
Images_23
Processing: matrix operationsg p
• The transpose image B (M * N) of A (N * M) can be• The transpose image B (M * N) of A (N * M) can be obtained as:B = A’
• The vertical flipped image B (N * M) of A (N * M) can be obtained as B fliplr(A)B = fliplr(A)
• The cropped image B (N1*N2) of A (N *M), starting from (n1; n2) can be obtained as:from (n1; n2), can be obtained as: B(k; l) = A(n1+k; n2+l)
• ...
• demo_simple_operationd i l ti 2• demo_simple_operation_2
• special_effects
Images_24
Converting Images to Other Typesg g yp
For certain operations it is helpful to convert an• For certain operations, it is helpful to convert an image to a different image type. example: filter a color image that is stored as an• example: filter a color image that is stored as an indexed image, you should first convert it to RGB formatRGB format.
• When you apply the filter to the RGB image, MATLAB filters the intensity values in theMATLAB filters the intensity values in the image, as is appropriate.
• If you attempt to filter the indexed image• If you attempt to filter the indexed image, MATLAB simply applies the filter to the indices in the indexed image matrix and the resultsin the indexed image matrix, and the results may not be meaningful.
Images_25
Converting Images to Other TypesTypes
• RGB to grayscale conversion• RGB to grayscale conversion
( ) ( ) ( )I p I p I p+ +( ) ( ) ( )( )
3R
R G Bgray
I p I p I pI p
I I I th d G Bl h l
+ +=
• grayscale to binary conversion
, , : Re , ,R G BI I I are the d Green Blue channels
grayscale to binary conversion
( ) 1 ( ) 0I p if I p threshold else= ≥( ) 1 ( ) 0bin grayI p if I p threshold else= ≥
Images_26
Images_27
Image data conversionsg
i d2 i d d t i t it• ind2gray - indexed to intensity• int2rgb - indexed to RGBg• gray2ind - intensity to indexed• rgb2ind - RGB to indexed• rgb2ind - RGB to indexed• mat2gray - matrix to intensity image• im2bw - threshold image to create binary image• im2double - image array to double arrayg y y• im2uint8 - image array to 8-bit int array• im2uint16 image array to 16 bit int• im2uint16 - image array to 16-bit int
Images_28• demo_image_conversion
Image Arithmetic Functionsg
• imabsdiff Compute absolute difference of two images• imabsdiff - Compute absolute difference of two images.
• imadd - Add two images, or add constant to image.
• imcomplement - Complement image.
• imdivide - Divide two images, or divide image by constant.
• imlincomb - Compute linear combination of images.imlincomb Compute linear combination of images.
• immultiply - Multiply two images, or multiply image by constant.
• imsubtract - Subtract two images, or subtract constant from image.
• demo_imsubtractdemo_imlincomb
Images_29
Histogramg
A graph indicating the number of times each• A graph indicating the number of times each gray level occurs in the image, i.e. frequency of the brightness value in the imagethe brightness value in the image
• The histogram of an image with L gray levels is represented by a one-dimensional array with Lrepresented by a one-dimensional array with Lelements.
• Algorithm:• Algorithm:– Assign zero values to all
elements of the array h ;elements of the array hf; – For all pixels (x,y) of the
image f incrementimage f, increment hf[f(x,y)] by 1.
Images_30
Dark image
Bright image
Images_31
Low contrast imageg
High contrast gimage
Images_32
Spatial Image Transformations p g
“I i l l f i ” “ i l i ”• “Intensity or graylevel transformation”, “pixel mapping”
• Typically implemented with a lookup table
Images_33Contrast Stretch Threshold
Simple Thresholdingp g
Why threshold?• Simplify image, make it easier to
analyse • Useful when we are interested inUseful when we are interested in
the shape of the objects.• To construct a mask.
Disadvantages• Throws away informationy• Threshold must generally be
chosen by hand• Not robust: different thresholdsNot robust: different thresholds
usually required for different images
>>im2bw
Images_34
Simple Thresholdingp g
demo simple threshold_ p _
Images_35
imadjustj
>>g=imadjust(f,[low in high in],[low out g j ( ,[ _ g _ ],[ _high_out],gamma)
• demo imadjust_ j
O i i “d k ” O i i “b i h ”Images_36
Output image is “darker” Output image is “brighter”
Tipsp
Ch k S Eddi ’ Bl• Check Steve Eddins’ Bloghttp://blogs.mathworks.com/steve
• Overview of the Image Processing Toolboxhelp images
• demo_rice_analysis
Images_37