Plotting in Matlab
by Matt Dunham
Matlab has excellent support for data visualization and graphics with over 70 types of plots currently available. We won’t be able to go into all of them here, nor will we need to, as they all operate in very similar ways. In fact, by understanding how Matlab plotting works in general, we’ll be able to see most plot types as simple variations of each other. Fundamentally, they all use the same basic constructs.
Contents
- Useful Functions
- Plotting 2D Data
- Plotting 2D Functions
- Handles and Customization
- 3D Surface and Contour Plots
- Interpolation
- Annotations and the Plot Editor
- Latex
- Coordinate Conversion
- Multiple Axes Per Figure
- Other Types of Plots
- Root Properties
- Saving and Printing
- Rotating Figures and Creating Movies
- User Input & Callbacks
- Custom Functions
Useful Functions
- figure, clf, close, hold, axes, gcf, gca, set, get
- axis, grid, title, xlabel, ylabel, zlabel, legend, box, annotation
- shading, material, camlight, alpha, view, colormap, colorbar, linespec
- plot, plot3, surf, surfc, contour, contourf, mesh, bar, bar3, pie3,
- loglog, semilogx, semilogy, hist, histc
- fplot, ezplot, ezsurf, ezcontour, ezmesh
- meshgrid, griddata, peaks,
- copyobj, allchild, findobj, findall, ancestor, ishandle
- camorbit, pause, camdolly, campan, camzoom, camroll, avifile, movie
- subplot, print, ginput, gtext, placeFigures
Plotting 2D Data
The best way to learn how to plot is to see many examples so we’ll jump right in and plot some data using the plot() command.
rand('twister',0); % seed the random number generator X = 5*rand(100,1); y = rand*X + rand(100,1); % generate some synthetic data f1 = figure; % create a blank figure p1 = plot(X,y,'.'); % plot X vs y
We have told Matlab to plot the data in X vs the data in y and to display a blue solid dot for each data point. There are many different types of marker and line styles available. For a complete list type doc linespec. Lets make a few changes. Recall that we can break long statements into multiple lines using ellipses, …
clf(f1); % clear the figure p2 = plot(X,y,'o','MarkerEdgeColor','k',... % plot larger red circles with black edges 'MarkerFaceColor','r',... 'MarkerSize',8); axis([-1,6,-1,5]); % set the axis limits
Plotting 2D Functions
Plotting functions is very similar to the data plotting we just performed. We begin by creating two functions, (see the section on function handles) and a grid of points, the domain. We then evaluate each function at every point along this domain and plot the resulting x,y pairs, connecting consecutive dots. Here we plot both functions on the same set of axes.
f = @(x) x.^2; % create a function of x, namely f(x) = x.^2 g = @(x) 5*sin(x)+5; % create a second function of x, g(x) = 5*sin(x) + 5 res = 0.001; % resolution of the plot domain = -pi:res:pi; % the domain of x, (i.e. points at which to evaluate f,g) f2 = figure; % open a new figure p3 = plot(domain,f(domain)); % plot f, w.r.t. x over its domain hold on; % tell Matlab to add future plots to the same set of axes p4 = plot(domain,g(domain)); % plot the second function.
Not bad for a first attempt but there are a lot of improvements we could make. Lets try again but this time, we will plot each function in its own color, change the line widths and types, the tick marks, the range of the axes, the background color, the font size, and add labels, a title, and a legend. We’ll keep the functions and domain the same. Let us also add error bars to one of the functions denoting one standard deviation of the dependent variable.
f3 = figure('Color',[1,1,1]); hold on; % new figure with a white background p5 = plot(domain,f(domain),'--r','LineWidth',3); % plot a thick dashed red line p6 = plot(domain,g(domain),'-b','LineWidth',3); % plot a thick solid blue line subdomain = domain(1:400:end); % we will plot error bars at every 400th point oneSTD = std(g(domain)); % standard deviation of g(domain) oneSTD = oneSTD*ones(size(subdomain)); % make correct size, as needed by errorbar p7 = errorbar(subdomain,g(subdomain),oneSTD); % plot the error bars title('example figure','FontSize',12); % add a title xlabel('distance','FontSize',12); % label the horizontal axis ylabel('height','FontSize',12); % label the vertical axis axis([-3,3,-5,15]); % set the axis range grid on; % add grid lines

Handles and Customization
Figure generation in Matlab is object oriented. Figures are top level objects and contain other objects such as axes and annotations. Axes further contain sub-objects such as plots and labels, which are often built up from smaller objects too. All of these objects have attributes that can be retrieved and, (for the most part) changed, using the get() and set() commands. The first parameter to these functions is a handle to an object. We can obtain such handles when we create the objects as in fig = figure.
After the fact, we can obtain the handle to the current figure by using the gcf() command or to the current set of axes by using the gca() command. We can also obtain handles to other types of objects using the findobj(), findall() , ancestor() ,and allchild() functions, but since this is very rarely necessary, we will not go into it here. Read their help entries if you are interested. We can see a list of all of the attributes of an object by typing get(handle) at the command prompt. The command set(handle) lists not only the attributes but also valid potential values.
We can test if a variable is a valid handle or not with the ishandle() method. Figure handles are actually just integer values starting at 1 that have been registered with the root graphics object.
Below, we use the set() method to change a number of axes attributes. Multiple attributes can be changed in one command, (or in multiple commands if you prefer) and the name of the attribute always precedes its new value.
set(gca,'box' ,'on' ... % draw a box around the figure ,'LineWidth', 2 ... % increase the line width ,'FontSize' ,12 ... % increase the font size ,'XTick' ,[-3,0,3]... % only these x-ticks ,'YTick' ,[0,5,10]); % only these y-ticks Xequal = domain(abs(f(domain) - g(domain)) < 2*res); % find where the two graphs meet p8 = plot(Xequal,f(Xequal),'o','MarkerFaceColor','g'... % plot green circles there ,'MarkerEdgeColor','k'... % black border around circles ,'LineWidth' , 2 ... % thicken black border ,'MarkerSize' ,10); % increase the circle size legend([p5,p6,p8],{'f(x) = x^2','g(x) = 5*sin(x)+5','f(x) == g(x)'},'Location','NorthWest'); % Prevent close commands from closing this figure. We will use it again later. set(f3,'HandleVisibility','off');
As you can see, most plotting commands, such as legend() above, have many possible parameters and parameterizations. It would be redundant to go into them all here; type doc legend ,for example, to see more information on the legend command.
There are Matlab functions designed to make function plotting easier such as fplot() , ezplot() , ezsurf() , ezmesh() , ezcontour() , etc… While these can be useful for quick and dirty figures, they can make customization more difficult and so we recommend using, and learning to use, plot() instead. All of these functions take function handles as arguements and the ez*** functions auto set the axes limits for you.
The loglog() , semilogx() , and semilogy() functions are useful for plotting on logarithmic scales. However we can achieve the exact same effect by plotting with plot() and calling set(gca,’XScale’,'log’) and/or set(gca,’YScale’,'log’) . We can reverse the direction of an axis with set(gca,’YDir’,'reverse’) or set(gca,’XDir’,'reverse’) and move an axis with set(gca,’YAxisLocation’,'right’) or set(gca,’XAxisLocation’,'top’) . Recall that we can find the names of these properties with get(gca) or the valid values with say set(gca,’YDir’) .
Many plotting functions, plot() in particular, but also line() and scatter() ,allow you draw multiple curves, lines or batches of data with a single command. See their help entries for more information.
We will now examine a number of other types of plots before discussing more advanced plotting options, such as adding multiple axes per figure to display graphs side by side, or the inclusion of various annotations such as arrows, and text. We have already seen how to change basic properties such as line widths and color. Doing so can considerably improve the look of figures, especially when they will appear in external documents.
3D Surface and Contour Plots
To graph a function of two variables we need to first evaluate that function over a grid of points, not just a line as in the 2D case. We use the meshgrid() function to create such a grid. There are several 3d plot types available. Here we use surf(), which plots the surface of the function, contourf() , which plots the contour lines of a function and fills the area between them with color, and mesh() , which is similar to surf(), displaying a wire mesh rather than a solid surface. The colors used in each are specified by the current colormap and can be changed by using the colormap() command. Type doc colormap for a list of options. There are several other 3d plotting functions: plot3() for instance is the 3d generalization of plot().
f = @(x,y) exp(cos(sqrt(x.^2 + y.^2))); % a function of two variables d = -2*pi:0.1:2*pi; % domain for both x,y [X,Y] = meshgrid(d,d); % create a grid of points Z = f(X,Y); % evaluate f at every point on grid
Some functions, while still vectorized, will only operate on vectors and not matrices. The mvnpdf() function for example interprets a matrix of inputs, (say n-by-d), as n, d-dimensional inputs, not n*d 1-by-1 inputs. We can still plot such functions in 3D with a few small changes. After obtaining X and Y from meshgrid(), save X’s size, evaluate f by passing in X and Y as column vectors, (using the : operator), and then reshape the output Z back to the original size and continue as before.
[nrows,ncols] = size(X); % first obtain the size of X Z1 = f(X(:),Y(:)); % convert X,Y to column vectors and evaluate f Z1 = reshape(Z1,nrows,ncols); % reshape
Here are some more example plots.
f4 = figure; % create a new figure p9 = surf(X,Y,Z); % plot the surface of the function shading interp; % interpolate between the points material dull; % alter the reflectance camlight(90,0); % add some light - see doc camlight alpha(0.8); % make slightly transparent box on; % same as set(gca,'box','on')
f5 = figure; % create a new figure p10 = contourf(X,Y,Z); % contour plot colorbar; % add a colorbar set(gca,'XTick',[],'YTick',[]); % remove all ticks
f6 = figure; % create a new figure r = 1:3:126; % mesh plots look better at lower resolution p11 = mesh(X(r,r),Y(r,r),Z(r,r)); % plot a mesh grid view([-15 60]); % change the viewing angle - see doc view colormap Copper; % change the colormap axis off; % turn off the axis completely
Note, the command view([90,90]) can be very useful to rotate a plot by 90 degrees, effectively reversing the locations of the x and y axes.
Below we display a 3d bar plot of the same underlying data. We take advantage of the mat2cell() command to partition the Z data into 21×21 6-by-6 blocks, each block stored within a cell. We then use the cellfun() function to replace each block with its mean. We can use this same technique to apply any function to arbitrary sized blocks of a matrix. Note that when the size of the data within cells is different, ‘UniformOutput’ must be set to false.
f7 = figure; grouped = mat2cell(Z,6*ones(21,1),6*ones(21,1)); % partition matrix into 6-by-6 blocks fconv = @(X)mean(X(:)); % create function handle convCell=cellfun(fconv,grouped,... 'UniformOutput',false); % apply that function to every block convMat = cell2mat(convCell); % convert back to a, (smaller) matrix p12 = bar3(convMat); % display a 3d bar plot of the aggregated data colormap jet % change the color map
Virtually everything we said about customizing 2D plots applies equally to 3D plots. We can add a title, a legend, labels using xlabel() , ylabel() , and zlabel() , change the range of the axes, the font size, etc.
Interpolation
3D plotting in Matlab requires a uniform grid of points but the data we obtain from experiments or measurements may not satisfy this constraint. In such cases, we can use the griddata() function to interpolate along a uniform grid of points for us.
f8 = figure; randn('state',0); % seed the normal random num generator X = randn(100,50); % data captured at these points. Y = randn(100,50); Z = cos(X.^2).*exp(X.^2 - Y.^2); % value of data at these points d = -1:0.1:1; % X,Y range of our data [XI, YI] = meshgrid(d,d); % create our grid as before ZI = griddata(X,Y,Z,XI,YI); % interpolate to obtain ZI p13 = mesh(XI,YI,ZI); % mesh of the interpolated points
Annotations and the Plot Editor
Matlab provides an interactive graphical interface for modifying and inspecting existing figures. This mode can be entered by selecting ‘view->Figure Palette’ or by selecting the appropriate shortcut button on the figure toolbar. Here we can add annotations such as text, arrows, and shapes as you would in a program like powerpoint. We can also inspect and change attributes as an alternative to using set() and get() .
Once you have added elements, you can see the m-code that generates these objects by going to ‘File -> Generate M-File’. It is usually easier to add annotations graphically first, generate the m-code and then add the appropriate lines to the original source file so that we can regenerate the complete figure at will. Alternatively, you can save a Matlab figure as a .fig file maintaining all of the graphics object information for future editing.
We will now add a few annotations to one of the previous figures. Annotations are placed relative to the figure window, not the axes. The location is, by default, specified by normalized coordinates between 0 and 1 so that [0.8 0.4] is the point 80% of the width from the left and 40% of the height from the bottom. In the case of a line or an arrow, we specify two x-y pairs, denoting the start and end points. In the case of a text box we specify four numbers, the x and y coordinates followed by the width and height of the box. Type doc annotation for more information. These commands were generated automatically after adding the annotations in the plot editor.
figure(f3); % the text arrow annotation(f3, 'textarrow' , [0.6616 0.5251],[0.1997 0.3038] ,... 'TextEdgeColor' , 'none' ,... 'TextLineWidth' , 2 ,... 'FontSize' , 12 ,... 'String' , {'global minimum'} ,... 'HeadStyle' , 'deltoid' ,... 'LineStyle' , '--' ,... 'LineWidth' , 2 ,... 'Color' , [0.07843 0.1686 0.549] ); % the dotted line annotation(f3, 'line' , [0.7176 0.7176],[0.7176 0.4154] ,... 'LineStyle' , '-.' ,... 'LineWidth' , 1 ,... 'Color' , [0 0 1] ); % the text box annotation(f3, 'textbox' , [0.59 0.47 0.15 0.05] ,... 'String' , {'g(c) - f(c)'} ,... 'FontSize' , 12 ,... 'FitBoxToText' , 'off' ,... 'LineStyle' , 'none' ); set(f3,'HandleVisibility','on');
Latex
Matlab supports the inclusion of both tex and latex markups in figures. This can be useful when you want to include mathematical formulas. For many purposes, simple tex is sufficient. For example, you can write super scripts with the ^ character and subscripts with the _ character, (notice the legend) and include Greek letters using say \alpha or \gamma. To include more complicated latex markups, you have to specify that you want to use the latex interpreter and then surround the mathematical text in $ symbols as shown below. Tex and Latex markups are supported in annotations, legends, and titles but unfortunately not in axis labels via the xlabel() , ylabel() , zlabel() commands or in axis tick labels. If you want to use latex in these locations, you have to add the text manually via annotations.
annotation(f3, 'textbox' , [0.2277 0.6333 0.2081 0.0625] ,... 'Interpreter' , 'latex' ,... 'String',{'$M_e = \frac{M_o}{\sqrt{1 - \frac{v^2}{c^2}}}$'},... 'FontSize' , 14 ,... 'FitBoxToText' , 'on' ,... 'LineStyle' , 'none');
Coordinate Conversion
Sometimes we would like to specify where an annotation should go relative to the current set of axes, rather than relative to the figure window as a whole. For instance, perhaps you would like an arrow to point at coordinate (3,4) on your current axes; what point is this relative to the whole figure? Below is some code to perform this conversion. Save it to a file and uncomment the code to create the function rel2abs() .
function [xabs,yabs] = rel2abs(xpos,ypos) ax = gca; xlim = get(ax,'xlim') ; ylim = get(ax,'ylim'); xmin = xlim(1) ; xmax = xlim(2); ymin = ylim(1) ; ymax = ylim(2); xscale = xmax - xmin ; yscale = ymax - ymin; axAbs = get(ax,'Position'); xabs = axAbs(1) + ((xpos-xmin) ./ xscale).*axAbs(3); yabs = axAbs(2) + ((ypos-ymin) ./ yscale).*axAbs(4); end
Multiple Axes Per Figure
Sometimes it can be useful to display multiple sets of axes in a single figure, perhaps to connect them graphically via annotations or just display them next to each other in a compact and convenient way. If we want the axes evenly spaced in a grid, the subplot() command can be useful but to have more varied and customizable configurations, we have to add the axes manually. To do so, we take advantage of the ‘Parent’ attribute of the graphics objects. Recall that figures are composed of axes and annotation objects and axes are composed of various plot objects. We will create a new plot and add it along with some of the plots we have already done. The copyobj(h,p) function copies a graphics object with handle h and assigns the new object to parent p.
f9 = figure; % create new figure sp = 0.05; % space between axes in % w = 0.2667; % size of each fig edge colormap gray; % make them all black & white for i=4:6 figure(i+1); % open the figure set(copyobj(gca,f9),'Position' ,... % copy object and set its position [sp+(i-4)*(w+sp),2*w+3*sp,w,w]); end newAx = axes('Parent',f9,'Position',... % create new axes [2*sp+w,2*sp+w,w,w]); surfc(peaks,'Parent',newAx); % plot built in function for i=7:8 figure(i+1); % open figure set(copyobj(gca,f9),'Position' ,... % copy object and set position. [sp + (i-7)*(2*w+2*sp),sp,w,w]); end
Note, we call figure(i+1) here rather than figure(i) because a Matlab document publishing anomaly offsets the figure handles by one. Normally you would go figure(i).
Recall that the hold command applies to axes objects and not figure objects. Keep this in mind when debugging problems you might face with multiple axes.
Other Types of Plots
There are many other types of plots supported by Matlab; we briefly show how to create a few of them here.
Create a 3d pie chart and ‘explode’ the largest piece.
figure; data = [2 4 9 3 7 2 1 1]; % some hypothetical data explode = double(data == max(data)); % turn on bit corresponding to largest piece pie3(data,explode); % create a 3d pie chart colormap jet; % set the color scheme
Plot the normal distribution and shade the tails using an area() plot. Add a small stem plot using the stem() command.
figure; domain = -4:0.01:4; % We shade two regions with the area command area(domain(1:fix(end/3)),normpdf(domain(1:fix(end/3)))); hold on; area(domain(fix(2*end/3):end),normpdf(domain(fix(2*end/3):end))); plot(domain,normpdf(domain),'-r','LineWidth',3); stem([-0.7,0.1,0.4],normpdf([-0.7,0.1,0.4]),'LineWidth',2); axis([-4,4,0,0.5]); set(gca,'XMinorTick','on'); % Include minor tick marks too set(gca,'YMinorTick','on'); grid on;
Display a histogram of a hypothetical class grade distribution.
figure; grades = fix(normrnd(70,10,100,1)); hist(grades); % plot the histogram xlabel('percent'); ylabel('count'); title('grade distribution'); set(gca,'XLim',[0,100],'YGrid','on'); set(gca,'YMinorTick','on');
Here we organize marks into bins representing letter grades. We use the extremely quick histc() function to count the number of data points that fall between specified edges. Once we have obtained the counts, we can visualize them with the bar() function.
figure; bins = [0,50,55,60,64,68,72,76,80,85,90,inf]; % The bins letters = {'F','D','C-','C','C+','B-','B','B+','A-','A','A+'}; % The labels counts = histc(grades,bins); % count grades bar(counts(1:end-1)); % plot counts set(gca,'XTickLabel',letters,'Ygrid','on'); % set tick labels xlabel('grade'); ylabel('count'); title('grade distribution'); set(gca,'YMinorTick','on')
There are many other plot types available. Search help for ‘Figures, Plots, and Graphs’ for a full list.
Root Properties
The top level Matlab graphics object is root and its handle is 0. We can access and set the root attributes as we would any other graphics handle object using get(0) and set(0). Root’s most useful attribute is probably ‘ScreenSize’, which gives the current size, (resolution) of the screen in pixels, by default, or in what ever units the ‘Units’ property has been set to. If you work with multiple simultaneous monitors, the ‘MonitorPositions’ attribute is also useful. Here we obtain the screen size and demonstrate how to maximize a figure programatically.
set(0,'Units','pixels'); % set the units to pixels screenSize = get(0,'ScreenSize') % get the monitor resolution hgap = 5; vgap = 45; width = screenSize(3)-2*hgap; height = screenSize(4)-2*vgap; newPosition = [hgap,vgap,width,height]; f = figure('Position',newPosition,'ToolBar','none'); % set the size and position close(f); % close the figure
screenSize =
1 1 1280 1024As root is the top level graphics object, we can query it for a list of the handles of all of the current figures using the allchild() function.
handles = allchild(0)'
handles = Columns 1 through 13 14 13 12 11 9 8 7 6 5 10 4 3 2 Column 14 1
Window size defaults and related settings as well as the maximum recursion limit is also set here; I suppose for lack of a better place.
Saving and Printing
We can print figures and save them as any major graphics type from the file drop down menu of a figure window. Also here is the ‘export setup’ option which opens a window where the default figure resolution and size settings can be set. Newer versions of Matlab also let you automatically increase the line widths and font sizes of the figures you are exporting. To save or print programatically, we can use the print() function. Here we save the figure as a jpeg. Type doc print for more details.
figure(f8); print -djpeg c:\windows\temp\test.jpg % save the current figure as a jpeg
If you find that there is too much white space surrounding the exported figure, (a particular problem when exporting to pdf) try changing the figure’s paper size before exporting, with the following commands.
pos = get(gcf,'Position'); set(gcf,'PaperSize',pos(3:4)); set(gcf,'PaperPositionMode','auto'); close(f8);
Rotating Figures and Creating Movies
Figures can be rotated or moved with the mouse by first clicking on the appropriate shortcut button on a figure window toolbar. However, we can also automate and animate the rotation by using the camorbit() command.
figure(4); % bring this figure to the foreground. axis vis3d % allow for rigid 3d rotation for i=1:36 % change camera angle 36 times camorbit(10,0,'camera') % 10 degree increments pause(0.01); % slow it down slightly end close(4);
We can also create a movie by capturing frames using the getframe() command and playing them with the movie() function. Alternatively we can create an avi file with the avifile() , and addframe() functions. Read their help entries for more information and examples.
There are many other functions that can be used to adjust the camera angle and motion such as camdolly() , campan() , camzoom() , and camroll() .
User Input & Callbacks
Matlab has good support for the creation of graphical user interfaces. To launch an interactive GUI builder, type guide at the command prompt. Here, we will only briefly touch on some of the ways in which users can interact with figures. To learn more about creating GUIs type doc guide and click on “Creating GUIs” at the bottom of the help page.
We will begin by discussing the ginput() function, which returns a matrix of coordinates selected with the mouse. Let’s bring up the second plot we made, call ginput() and select a few data points to return their coordinates. ginput(n) waits for n user clicks before returning the n points, whereas ginput() , without any parameters, allows you to select any number you like and returns only when the user presses the enter key. A similar function, gtext(txt) places the specified string at the location selected by the mouse.
figure(f1); C = ginput(5) close(f1);
C =
1.8468 1.2719
1.7984 1.3947
1.7984 1.6053
1.8790 1.7281
2.1855 1.7105The above functions operate by assigning a callback function to the axes object, which gets executed whenever the user clicks within the axes. We can assign our own function to perform whatever action we wish when this happens. Most Matlab graphics objects have callback attributes, which can be viewed using the get() command and set using set() .
The only constraint on callback functions is that they take 3 or more parameters as in myCallback(hObject, eventdata, handles): hObject is the object selected, whereas eventdata, and handles differ depending on the the callback. For more information, search for CallBack Syntax and Arguments in help.
All graphics objects in Matlab also have a ‘UserData’ attribute, which can be assigned any data you like. Since the clicked object is returned in hObject, we can retrieve this data with get(hObject,’UserData’).
In this simple example, we plot 5 points in 5 different plots and assign each plot’s ‘UserData’ attribute a color’s name, which we will display when clicked. Since this is a simple example, we can create the callback inline but in general you should create a stand alone function say function myCallback(hObject,eventData,handles) and then assign @myCallback to the object’s callback attribute. We also assign the callback to the current axes and figure objects after setting their ‘UserData’ entries to their respective colors. Try out the code for yourself.
figure; hold all; name = {'red','blue','green','magenta','cyan'}; color = {'.r','.b','.g','.m','.c'}; loc = [(1:5)',2*ones(5,1)]; callback = @(hObject,eventData,handles)display(get(hObject,'UserData')); for i=1:numel(name) plot(loc(i,1),loc(i,2),color{i},... 'MarkerSize',100,'UserData',name{i},... 'ButtonDownFcn',callback); end axis([0,6,1,3]); set(gca,'UserData','white') % Set the axes user data set(gca,'XTick',[],'YTick',[],'box','on'); set(gca,'ButtonDownFcn',callback); % assign the callback set(gcf,'UserData','grey'); % set the figure user data set(gcf,'ButtonDownFcn',callback); % assign the callback
Custom Functions
When many figures are generated at once, it can be difficult to organize them all on the screen. The placeFigures() function, available below automatically organizes figures on the screen for you. Simply call placeFigures after generating the figures. You can specify the layout manually with say placeFigures(‘nrows’,2,’ncols’,4) , create new blank figures with the ‘newfigs’ option and display figures on a second monitor with the ‘monitor’ option. See the function documentation for more options and examples.
Popularity: 2% [?]
A NURBS Toolbox for Matlab
This week we point on the Nurbs toolbox from Paul Zhang.
It may not be very fast since it is completely MATLAB coded but it is very well coded and helpful. It offers utily not only to draw Nurbs patches but to compute differential properties and geometric transformation.
With some imagination you can use this toolbox to build your 3D CAD inside Matlab.
The list of functions includes:
- Nurbs
- nrbmak – Construct a NURBS from control points and knots.
- nrbtform – Applying scaling, translation or rotation operators.
- nrbkntins – Knot insertion/refinement.
- nrbdegelev – Degree elevation.
- nrbderiv – NURBS representation of the derivative.
- nrbdeval – Evaluation of the NURBS derivative.
- nrbkntmult – Find the multiplilicity of a knot vector.
- nrbreverse – Reverse evaluation direction of the NURBS.
- nrbtransp – Swap U and V for NURBS surface.
- nrbline – Construct a straight line.
- nrbcirc – Construct a circular arc.
- nrbrect – Construct a rectangle.
- nrb4surf – Surface defined by 4 corner points.
- nrbeval – Evalution of NURBS curve or surface.
- nrbextrude – Extrude a NURBS curve along a vector.
- nrbrevolve – Construct surface by revolving a profile.
- nrbruled – Ruled surface between twp NURBS curves.
- nrbcoons – Construct Coons bilinearly blended surface patch.
- nrbplot – Plot NURBS curve or surface.
- B-Spline
- bspeval – Evaluate a univariate B-Spline.
- bspderiv – B-Spline representation of the derivative
- bspkntins – Insert a knot or knots into a univariate B-Spline.
- bspdegelev – Degree elevation of a univariate B-Spline.
- Transformations
- vecnorm – Normalise the vectors.
- vecmag – Magnitaude of the vectors.
- vecmag2 – Squared Magnitude of the vectors.
- vecangle – Alternative to atan2 (0 <= angle <= 2*pi)
- vecdot – Dot product of two vectors.
- veccross – Cross product of two vectors.
- vecrotx – Rotation matrix around the x-axis.
- vecroty – Rotation matrix around the y-axis.
- vecrotz – Rotation matrix around the z-axis.
- vecscale – Scaling matrix.
- vectrans – Translation matrix.
- Utility
- deg2rad – Convert degrees to radians.
- rad2deg – Convert radians to degrees.
Download Now
Popularity: 1% [?]
Geometric Primitives and Geomtric Operations with Matlab
Matlab does not come by default with a geometric primitives library. About for some simple function like the “sphere” command, using some geometric entities may be an issue. Fortunately on Matlab file exchange are available these two packages, from David Legland ,that help us to develop geometric projects.
- Geom2DÂ Download Now
- Geom3DÂ Download Now
The packages include functions for computations on planar and spatial geometrical shapes (points, lines, circles, polygons…)
The goal is to provide a low-level library for manipulating geometrical primitives, making easier the development of more complex geometric algorithms.
The library proposes functions to:
- create various shapes (points, circles, lines, ellipses, polylines, polygons) using an intuitive syntax. Ex: createCircle(p1, p2, p3) to create a circle through 3 points.
- derive new shapes: intersection between 2 lines, between a line and a circle, parallel and perpendicular lines
Functions to compute intersections - work on polylines and polygons: compute centroid and area, expand, clip with half-plane…
- measure distances (between points, a point and a line, a point and a group of points), angle (of a line, between 3 points), or test geometry (point on a line, on a circle).
- manipulate planar transformation. Ex: P2 = transformPoint(P1, createRotation(CENTER, THETA));
- draw shapes easily. Ex: drawCircle([50 50], 25), drawLine([X0 Y0 DX DY]). Some clipping is performed for infinite shapes such as lines or rays.
- functions for 3D polygons and polyhedra. Polyhedra use classical vertex-faces arrays (face array contain indices of vertices), and support faces with any number of vertices. Some basic models are provided (createOctaedron, createCubeoctaedron…), as well as some computation (like faceNormal or centroid)
- direct drawing of shapes with specialized functions. Clipping is performed automatically for unbounded shapes such as lines or rays. Ex:
drawPoint3d([50 50 25; 20 70 10], ‘ro’); % draw some points
drawLine3d([X0 Y0 Z0 DX DY DZ]); % clip and draw straight line
Popularity: 1% [?]




































































