124 Downloads

Updated 24 Feb 2004

No License

**Editor's Note:** This file was selected as MATLAB Central Pick of the Week

SURF2STL Write STL file from surface data.

SURF2STL('filename',X,Y,Z) writes a stereolithography (STL) file

for a surface with geometry defined by three matrix arguments, X, Y

and Z. X, Y and Z must be two-dimensional arrays with the same size.

SURF2STL('filename',x,y,Z), uses two vector arguments replacing

the first two matrix arguments, which must have length(x) = n and

length(y) = m where [m,n] = size(Z). Note that x corresponds to

the columns of Z and y corresponds to the rows.

SURF2STL('filename',dx,dy,Z) uses scalar values of dx and dy to

specify the x and y spacing between grid points.

SURF2STL(...,'mode') may be used to specify the output format.

'binary' - writes in STL binary format (default)

'ascii' - writes in STL ASCII format

Example:

surf2stl('test.stl',1,1,peaks);

See also SURF.

Author: Bill McDonald, 02-20-04

Bill McDonald (2021). surf2stl (https://www.mathworks.com/matlabcentral/fileexchange/4512-surf2stl), MATLAB Central File Exchange. Retrieved .

Created with
R13

Compatible with any release

**Inspired:**
stlwrite - write ASCII or Binary STL files, surf2solid

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

Jeremy HuMarco Ferrara@Hrushikesh did you resolve?

HrushikeshI have created implit surface for unit cell of I-wp TPMS lattice using following:

f = @(x,y,z) 2 * (cos (pi*x/2) * cos(pi*y/2) + cos(pi*y/2) * cos(pi*z/2) + cos(pi*z/2) * cos(pi*x/2)) - (cos(2 * pi*x/2) + cos(2*pi*y/2) + cos(2*pi*z/2));

fimplicit3(f,[-2 2 -2 2 -2 2])

How can I proceed to get this surface as .stl file?

Wang Jack@Amir Minoofar

Usage:

[x,y] = meshgrid(0:0.1:16*pi,0:0.1:8*pi);

z = 2.*cos(.4*x).*sin(.4*y);

mesh(x,y,z);

surf2stl('surf.stl',x,y,z);

Amir MinoofarWould it be possible for someone to tell me what should I do?

It gives me error and says unable to write the file.

Unable to write to test.stl

I'm using a simple one just for test:

[X,Y] = deal(1:40); % Create grid reference

Z = peaks(40); % Create grid height

surf2stl('test.stl',X,Y,Z)

Paul KenneyChunghwan JungRyan ChangWorked for my surface which I created from griddata and surf functions - thanks!

Craig PuetzI have been trying to use this code without success. I can generate 3D plots using the Matlab commands trisurf and surf. I have plotted with both latitude, longitude coordinates, and with a distance based grid that I generated using meshgrid. Some of my data contains NaN as the surface is not a rectangular area. I have tried removeing these points, as well as setting them all to a floor that is slightly below my lowest real altitudes.

I haven't had success with any of these data sets. The results from surf2stl (and also from other Matlab Central routines stlwrite and surf2solid) is a flat plane, located on a Z coordinate system that I do not understand. Can anyone help with ideas? Thanks in advance.

Matthias NoackHello I like really this function but I only get 1 single sphere which is always in the same position. I would like to get randomly distributed spheres in the space as stl.

I already have a function for random positions but how can I append spheres to an already existing stl with different positions? Would be great if you could help me :)

This is my code:

clear;

close all;

[x,y,z]=sphere;

r=1;

dimension=10;

figure;

hold on

grid on

axis([0 dimension 0 dimension 0 dimension]);

view(-45,25);

%%%%%%% Create Random Positions %%%%%%

for a=1:1:3 % --> 3 Dimensions (X,Y,Z)

for b=1:1:5 % --> 5 Spheres

pos(a,b)=randi((10/r)-1,1)*r; % --> Assing center points

end

end

%%%%%%% Plot spheres and create stl %%%%%%

for a=1:1:3

for b=1:1:5

surf(x*r+pos(1,b),y*r+pos(2,b),z*r+pos(3,b)); % --> Plot spheres

surf2stl('test3.stl',x*r+pos(1,b),y*r+pos(2,b),z*r+pos(3,b)) % --> Create stl

end

end

Ilya KubasovMatheusHello. I have a point cloud [X, Y, Z] matrix with x,y and z coordinates. How can I use this code to write a STL file with the surface?

Bewlerfid == -1 and is always unable to write stl?

Devon JakobNISHANT NILAYI have 6 variables: for Large sphere X,Y,Z and small sphere mounted over it P,Q,R and i want to convert the surf plot of these two sphere into a .stl file. Can you please help me?

Mostafa AyazCharming!!

Nikos MountakisChristopher HartmannIt works super good. But is it possible to change the direction of the normal vectors from pointing to the inside to pointing to the outside?

LiFujiaJoe HansenV slick my dude.

leegreat work Thanks

Adam YockThis was exactly what I needed. Thanks! Worked without any issues.

Xiangmu TianCarl WitthoftJohn Popefilename='link0_test.stl'; %base

cyl_radius=0.025;

cyl_height = 0.1;

precision = 40; % increase to obtain a more accurate drawing

%create a unit height cylinder with 100 points. Radius 75

[X,Y,Z] = cylinder([cyl_radius], precision);

%Multiply Z by height

Z=Z*cyl_height;

%Save in stl format, create new file

surf2stl(filename, X, Y, Z, 'ascii', 'w');

%now create a disk, bottom

radius = linspace(0,cyl_radius,precision); % For ten rings

theta = (pi/180)*[0:15:360]; % For eight angles

[R,T] = meshgrid(radius,theta); % Make radius/theta grid

X = R.*cos(T); % Convert grid to cartesian coordintes

Y = R.*sin(T);

%append this solid to already created file, bottom disk

surf2stl(filename, X, Y, 0.*X, 'ascii', 'a+');

%top disk

surf2stl(filename, X, Y, cyl_height.*ones(size(X,1), size(X,2)), 'ascii', 'a+');

https://github.com/teddyort/matlab/blob/5c7156b291d0633fbef714e0d8f4b308303dd366/robot-9.9/rvctools/contrib/arte3.2.3/robots/equipment/cylinders/create_cylinder.m

John Popeforget previous comment. digging through google results.... supposedly you need a meshgrid

https://www.mathworks.com/help/matlab/ref/meshgrid.html

[X,Y] = meshgrid(-2:.2:2, -4:.4:4);

Z = X .* exp(-X.^2 - Y.^2);

surf(X,Y,Z)

surf2stl('test.stl',X,Y,Z)

John PopeThis really could be simplified by moving the dimension detections within function (size(L):rows,size(L):cols)

here's how I got it working....

L needs to be 2 dimensional (rows,cols) l!!!!!

eg.

L = -0.1136 -0.1932 -0.0031 0.0593 -0.2272

0.2525 0.5000 0.9647 1.0000 0.0593

0 0 0 0.9647 -0.0031

0 0 0 0.5000 -0.1932

0 0 0 0.2525 -0.1136

surf2stl('logo.stl',size(L):rows,size(L):cols,L);

Mychal TaylorI'm trying to convert my .m file to a .stl file and I am having a hard time using this function. What do I put into the x y z componets in the surf2stl?

Tyler MooreIs there a way to create a volume using this script? I have the .stl surface, but want to extend that to some "ground" so I can print it with a 3D printer.

Carlos BezerraHi. I have cute solids by using trisurf(tri,xmesh,ymesh,zmesh,colorVector), where x(nx1), y(nx1), z(nx1) and tri(n/2 x 3). But, unfortunately it does not run at your surf2stl. Do you have any idea how can I run trisurf2stl? Thank you.

Arnaud GUILLOU-CAMARGOThomas-Glyn CoxDoes not work anymore

WesleyHi, I am trying to get MATLAB to output STL files of chaotic systems (Rossler, Lorenz, Chua). The graphs are made from iterating x, y, and z in a for loop. So I converted the vectors into a matrix using the vec2mat command. It gave me the STL files but the lines have no thickness. How can I resolve this problem? I tried adding space below the graph but it just makes a cylinder shape and doesn't thicken the lines. Please advise.

AdamL = 40*membrane(1,25);

[rows cols] = size(L);

x = 1:rows;

y = 1:cols;

surf2stl('logo.stl',x,y,L);

And voila! You can 3D print the Matlab logo! (or any other surface for that matter) =)

LEGAL NOTE: This may violate copyrights or trademarks. I am not liable if you choose to do this.

Thanks for the awesome code!

Algirdas KluoniusPlease help I get a flat gray surface, is it because my x ,y, are vectors and not meshgrid?

junquaReally usefull for my research with flow over different surfaces

Héctor CorteMan great submision. I have used it to make some geek gif in my blog.

http://thebrickinthesky.wordpress.com/2012/12/23/my-own-death-star/

zaeazeaeThanks for this file! You save me a lot of time! Very helpfull

Jay Bergernice work bill. i'm wondering about how one would go about adding labels to such stl files. such as, adding little spheres in a surface plot at a certain location (say x = 10, y = 10) and add labels such as "x = 10 & y = 10" at that location.

Samarth Raut@ Prashanth,

AFAIK, .stl is inherently meant for triangulated geometry representation.

http://en.wikipedia.org/wiki/STL_%28file_format%29

What you can do is to split rectangles into triangles - e.g. rectangle (n1, n2,n3,n4) gives two triangles - (n1,n2,n3) and (n3,n4,n1). Note that the order of n1,n2 etc is such that the normals obtained by cross product of vector, say n1_n2 x n2_n3 points outwards direction and there is consistency in this normal direction among all triagles. i.e. no sudden flips.

hope it helps,

Samarth

Mahalingam PaheerathanPrashanth hanmaiahgariHi Bill,

What changes to be made in the program to get a stl with rectangular grid instead of triangular grid

Thanks!

Prashanth

ZoltanNice!

But you could speed it up - it counts at large meshes, if you could find a way to avoid the for loop. For calculating the surface normals, you could use "surfnorm".

Thanks!

Bart RibbensGreat job! Thanx a lot!

Daniel LopesThanks Bill! You made a very useful MATLAB function for geometric modeling purposes.

Woks just fine!

Bin HuangAwesome! It helps me alot.

Max LingamfelterVery nice program. Does anyone know a way to write the STL file while keeping other data intact to describe the color?

maxami13@msn.com

Yoel ShapiroVery helpfull! I tried for a long time to open a MATLAB generated mesh or vrml in different 3D environments and couldn't. This did the job.

Amanda Lvery neat. Used for converting small pieces of scarcely digitized bone surface point clouds to STL surface which can be loaded into Mimics and Amira.

Mike MHas good nift. Use with gridgen to make mathematical surfaces into stl files for cfd. mmmm