Code covered by the BSD License  

Highlights from
stlwrite - Write binary or ascii STL file

4.9 | 20 ratings Rate this file 196 Downloads (last 30 days) File Size: 4.39 KB File ID: #20922
image thumbnail

stlwrite - Write binary or ascii STL file




30 Jul 2008 (Updated )

Export a variety of inputs (patch, surface) to an STL triangular mesh

| Watch this File

File Information

** Big speed boost courtesy of Oliver Woodford. Recommended to update to latest version **

  STLWRITE(FILE, FV) writes a stereolithography (STL) file to FILE for a
  triangulated patch defined by FV (a structure with fields 'vertices'
  and 'faces').

  STLWRITE(FILE, FACES, VERTICES) takes faces and vertices separately,
  rather than in an FV struct

  STLWRITE(FILE, X, Y, Z) creates an STL file from surface data in X, Y,
  and Z. STLWRITE triangulates this gridded data into a triangulated
  surface using triangulation options specified below. X, Y and Z can be
  two-dimensional arrays with the same size. If X and Y are vectors with
  length equal to SIZE(Z,2) and SIZE(Z,1), respectively, they are passed
  through MESHGRID to create gridded data. If X or Y are scalar values,
  they are used to specify the X and Y spacing between grid points.

  STLWRITE(...,'PropertyName',VALUE,'PropertyName',VALUE,...) writes an
  STL file using the following property values:

  MODE - File is written using 'binary' (default) or 'ascii'.

  TITLE - Header text (max 80 chars) written to the STL file.

  TRIANGULATION - When used with gridded data, TRIANGULATION is either:
                    'delaunay' - (default) Delaunay triangulation of X, Y
                    'f' - Forward slash division of grid quads
                    'b' - Back slash division of quadrilaterals
                    'x' - Cross division of quadrilaterals
                  Note that 'f', 'b', or 't' triangulations now use an
                  inbuilt version of FEX entry 28327, "mesh2tri".

  FACECOLOR - Single colour (1-by-3) or one-colour-per-face (N-by-3)
                  vector of RGB colours, for face/vertex input. RGB range
                  is 5 bits (0:31), stored in VisCAM/SolidView format

  Example 1:
      % Write binary STL from face/vertex data
      tmpvol = zeros(20,20,20); % Empty voxel volume
      tmpvol(8:12,8:12,5:15) = 1; % Turn some voxels on
      fv = isosurface(tmpvol, 0.99); % Create the patch object
      stlwrite('test.stl',fv) % Save to binary .stl

  Example 2:
      % Write ascii STL from gridded data
      [X,Y] = deal(1:40); % Create grid reference
      Z = peaks(40); % Create grid height

  Original idea adapted from surf2stl by Bill McDonald. Huge speed
  improvements implemented by Oliver Woodford. Non-Delaunay triangulation
  of quadrilateral surface courtesy of Kevin Moerman. FaceColor
  implementation by Grant Lohsen.

Note: This entry was originally titled "patch2stl", however has been renamed to "stlwrite" after more general input was added.


Surf2stl and Mesh2tri inspired this file.

This file inspired Stlwrite Write Binary Or Ascii Stl File, Export Voxel Data, and Puncture Surface.

MATLAB release MATLAB 7.13 (R2011b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (42)
05 Jan 2015 Alexander Kosenkov

Alexander Kosenkov

Very simple, clean and fast implementation!

26 Sep 2014 Thomas


Great work! And binary as well, i like it.

As a minor it would be cool to be able to specify the normals as well. (not that i couldn't do this myself, but it would save a minute ;) )

01 Sep 2014 Salaheddin Hosseinzadeh

Salaheddin Hosseinzadeh

09 Aug 2014 Luis Castro

Luis Castro


I Might you explain a little detail how to perform the conversion of stl right through points. I have 22050 points (xyz) belonging to the riverbed. My task is to generate an STL file.
In what format should I take the points?
As I run the compile stlwrite ?. They could give me the steps?
Please, could you help me.

Comment only
21 Jul 2014 Urlea


Thank you Sven,

Works out great


Comment only
14 May 2014 Sven


@Urlea: Yes, you can do this when (or after) you generate the faces/vertices.

If you are using the isosurface() function to generate your faces/vertices from a logical, remember that isosurface() will *always* produce faces pointing from low to high. In that case, you can just invert your logical mask (to have ones outside and zeros inside) when you call isosurface.

To flip faces after you've got faces vertices, just use the following:

fv.faces = fv.faces(:,[2 1 3])

Comment only
14 May 2014 Urlea


I am trying to Write binary STL from face/vertex data file with the example you give in your code. I then import the file generated in Magics (Materialise) and use an automatic tool to generate a diagnostig of the body. It says that all the faces are inverted (normals pointing inside out). Is there a way to fix this inside the Matlab code ?

Comment only
26 Mar 2014 Steve


Thanks so much!

23 Feb 2014 Adam Hart

Adam Hart


20 Feb 2014 Adam


Awesome! Thanks!

05 Oct 2013 Reza


Hi Friends,

Excellent job. I use it for a complex geometry which comes out of images. I created the .stl file but many surfaces are open and not connected. I want to have close surfaces with volume.

Thanks for your comments and help.

26 Sep 2013 Ben


@Sven: I have done both your tricks. I found the problem is not your code; it is the software I am using to view meshes. I tried Meshlab and ParaView. None of them works for color surface. Probably they work for the other interpretation. VisCam works well for this. Thanks!

25 Sep 2013 Sven


@Ben: Here's an example that uses the VisCam colour specification:

tmpvol = true(20,20,20); % Zeros on the inside means
tmpvol(8:12,8:12,5:15) = 0; % isosurface makes triangles
fv = isosurface(tmpvol, 0.5); % point out of object
faceColVal = fv.vertices(fv.faces(:,1),3); % Colour by Z height
cRange = [min(faceColVal) max(faceColVal)];
nCols = 255;
colMap = jet(nCols);
faceColsDbl = interp1(linspace(cRange(1),cRange(2),nCols),colMap, faceColVal);
faceCols8bit = faceColsDbl*255;
figure, patch(fv,'FaceVertexCData',faceColsDbl,'FaceColor','flat')

I used the free viewer here, and the colours show up nicely.

You'll notice two tricks in my code above.
1. Make sure your face normals are pointing outwards. VisCam only displays the outer sides with colour and the inner sides without.
2. Make sure you provide 8-bit scaled colours (ie, between 0 and 255 rather than MATLAB's 0 and 1).

Did that work out for you? I might include that as an example in the help as long as it still works for you. Note that there are two competing "interpretations" of colour in an STL file. This is just one of them so I hope your software can interpret it well.

Comment only
25 Sep 2013 Ben


Can anyone give an example of writing a stl file with per face color? I tried several times but did not make it.


Comment only
16 Aug 2013 Haojie


Works great!

27 Jun 2013 Ben


Very nice code and amazing fast! Thanks for sharing!

11 Apr 2013 JD


@Sven: Thanks. It worked like a charm! It didn't work when I tried to connect it with using triangulation in stlwrite but when I used used mesh2tri to generate the faces and vertices and then used those in stlwrite, it worked! Thanks a lot again for such a quick reply!

Comment only
11 Apr 2013 Sven


The issue is that your input is "gridded data" not "triangulated data" because each of x, y, z is a 20-by-20 matrix, rather than a set of vertices and triangles.
This can be handled by stlwrite (see the help file for the "triangulation" parameter), but you'll need to understand that the default "triangulation" of gridded data is a delaunayTri of the X-Y 2D data. In this sense you have repeated X-Y pairs (one at the top of the sphere, one at the bottom). The warning you're getting comes from "delaunay", not from "stlwrite".
You can overcome this by specifying how you want your gridded data triangulated:


Note that you'll need "mesh2tri" from for this to work. I will ask Kevin for permission to include it in stlwrite (it's a small but very handy function) for a next release.

Comment only
10 Apr 2013 JD


Hi! I am facing the same issues as Alexandra. I was trying to gererate surface mesh for a sphere and then converting into .stl format. When I tried to view it in Meshlab, one half of the sphere was gone. I did get a warining about duplicate data points.

Warning: Duplicate data points have been detected and removed.
Some point indices will not be referenced by the triangulation.

The commands I used are below:

Any help will be highly appreciated. Thanks.

Comment only
08 Oct 2012 Sven


@Alexandra, I'll bet that probably there are some duplicated/disjoint vertices in MATLAB prior to using stlwrite. Can you send me an example of the data that is coming through open?

Comment only
06 Oct 2012 Alexandra


I have the problem that I get open surfaces after using STLwrite. Has anybody an idea what to do about this?

02 Jul 2012 or litany

or litany

does anyone know how to show the different colors per face I used? I've tried meshlab and 3d max

Comment only
20 Jun 2012 Adam


Thanks for your help Sven, turns out the problem was in my import settings in Gambit. It needed to be a little different because of the more complex geometries in those files. Again, wonderful program!!

Comment only
19 Jun 2012 Sven


Ha, that last message was from me - logged on from another computer at work.

Comment only
19 Jun 2012 Binu


@Nick and Adam, I'm not sure what issues may be at play with your files. Feel free to email a .mat file with your points/faces data *and* the 2 or 3 lines you use to create a working(!) figure from this data in MATLAB (note that I'll only have time to look at it if the figure creates cleanly).

Comment only
19 Jun 2012 Adam


Great program. It worked fine for 2 of my files with relatively simple geometries, but one other didn't output a readable mesh (I tried to open it in both Solidworks and Gambit), the other didn't connect the mesh into triangles, there were just some points in Gambit. Both mesh just fine using the trimesh function. Any ideas?

02 Jun 2012 Nick


@Sven you've been very clear, thanks. i ask an other question, to better understand.

my set of p x-y-z describes a 3D surface that i can see properly in matlab (using plot3 or trisurf), as you say.

to write the stl, I can use directly the function "stlwrite"?
Does this make a triangulation of my 3D coordinates?

In that case, which options I have to give to the function to make it works properly? because I have tried many ways, but when i give 'triangulation' it wants other options and values, and I don't know what to put into.

thanks again!

Comment only
01 Jun 2012 Sven


@Nick: If you create a Delaunay triangulation from a set of p X-Y-Z points:

dt = DelaunayTri(x,y,z)

The result (dt.Triangulation) will not be a "triangular surface mesh". You'll notice that the result is an n-by-4 matrix. This means that each row in the triangulation represents a tetrahedron - a small *solid* with 4 triangular faces - not a surface triangle.

STL format describes surface triangles rather than tetra solids. Perhaps you want the convex hull of your points? (ie, only the *outermost faces* of all of your tetra solids) Note this will only work if your simple solid body is in fact convex.

Here's my advice: plot to the screen before trying to write to an STL file. If you can get a 3d surface plot (using patch, trisurf, etc) working in MATLAB first, *then* you will be able to write to STL without problems.

Comment only
01 Jun 2012 Nick


hi, I have a set of coordinates of a simple solid body, and I have to create finite volumes to work on. So I made a 3D Delaunay triangulation, and I have now a n-by-4 matrix with the points of resultant tetrahedron. Now, I need to create a .stl file to export this work. how do I do this? Is it possible? Because in the option There is only the voice for a triangulation in 2D. Thanks a lot.

Comment only
04 May 2012 Joachim


11 Mar 2012 Romain W

Romain W

03 Feb 2012 Sven


@ava: glad to hear that the issue (nodes indices) was resolved

Comment only
15 Jan 2012 ava


@Sven:I am using STL viewer and also MiniMagics 2.o to see the result file but all the faces are disconnected.

Comment only
14 Jan 2012 Sven


@ava: This is the first I've encountered such an issue. Does the same thing happen when you run the example in the stlwrite help? If not, try using the splitFV FEX entry to see if the original faces/vertices are indeed connected. If the stlwrite example itself comes out unconnected, what software do you use to read the .stl?

Comment only
14 Jan 2012 ava


Faces are not connected in the result stl. ,Does anyone have any idea?


Comment only
04 Jan 2012 William Thielicke

William Thielicke

Works nicely. For my old Matlab version, I had to remove one line to make it work:
narginchk(2, inf)

28 Nov 2011 Oliver Woodford

Oliver Woodford

Binary output is now very fast! :)

13 Oct 2011 Sven


The latest update has made significant speed improvements with vectorised face normal calculation and combining adjacent fwrite calls. Hope it's useful.

Comment only
13 Sep 2010 Oliver Woodford

Oliver Woodford

Works well, though very slow (in binary mode at least).

02 Jul 2009 Holger Roth

Holger Roth

Great! That's what I looked for...

28 Apr 2009 Georg Stillfried

Georg Stillfried

Worked fine!

02 Aug 2008 Scott Burnside

Nice companion to cad2matdemo.m. Very useful.

11 Oct 2011

Vectorised normal direction calculations and streamlined fprint/fwrite calls. 75% faster writing speeds.

17 Oct 2011

Allowed for more general input types, and added capability for more features to be written to STL file.

24 Nov 2011

Huge speed improvements courtesy of Oliver Woodford. Reduction in write-time is proportional to file size.

20 Aug 2012

Added faceColor implementation

11 Apr 2013

Embedded version of Kevin's mesh2tri for convenience.

Contact us