How to export a 3D surface (gyroid) into an STL file

15 views (last 30 days)
How do I export this Matlab code into an STL file for Solidworks and 3D printing?
[x,y,z] = meshgrid (-pi:pi/16:pi); % 3D coordinates defined by x, y, z
v = sin(x).*cos(y)+sin(y).*cos(z)+sin(z).*cos(x); % gyroid formula
t=0.5+0.1*z; % offset from isovalue, affects thickness
v=(v-t).*(v+t); % multiplies one negative offset gyroid and one positive offset gyroid
figure(1)
isosurface (x, y, z, v, 0);
hold on
figure(1)
isocaps(x,y,z,v,0,"below");

Answers (2)

Voss
Voss on 2 Jun 2022

DGM
DGM on 22 Jun 2025
Edited: DGM on 22 Jun 2025
FEX surf2stl() accepts gridded data, as would be used with surf(), but isosurface(), isocaps() produce FV data. This can be exported using built-in tools, but it takes a little bit of work to combine the data into a single object.
We want FV data to export, and we also want to display a plot. Tools like isosurface(), isocaps() can't plot and produce outputs one call, so we have three choices:
  1. call them twice
  2. use them to get FV data, then use patch(), etc to plot everything
  3. use them to do the plot, then get the FV data from the figure
I'm opting for #3. it's easy, the plotting is concise, and calculations aren't duplicated.
[x,y,z] = meshgrid (-pi:pi/16:pi); % 3D coordinates defined by x, y, z
v = sin(x).*cos(y)+sin(y).*cos(z)+sin(z).*cos(x); % gyroid formula
t = 0.5 + 0.1*z; % offset from isovalue, affects thickness
v = (v-t).*(v+t); % multiplies one negative offset gyroid and one positive offset gyroid
% find the isosurface and plot everything concisely
isosurface(x, y, z, v, 0); hold on
isocaps(x,y,z,v,0,"below");
axis equal; grid on
% combine the two FV sets
hp = findobj(get(gca,'children'),'type','patch');
F = [hp(1).Faces;
hp(2).Faces+size(hp(1).Vertices,1)];
V = vertcat(hp.Vertices);
% remove duplicate vertices
[V,~,ic] = unique(V,'rows');
F = ic(F);
% write to STL
T = triangulation(F,V);
stlwrite(T,'test1.stl')
% read it back just for show and tell
Trec = stlread('test1.stl');
figure
patch('faces',T.ConnectivityList,'vertices',T.Points,'facecolor','w','edgecolor','none');
view(3); view(-37,30); camlight;
axis equal; grid on
xlabel('X'); ylabel('Y'); zlabel('Z')

Tags

Products

Community Treasure Hunt

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

Start Hunting!