I'm trying to export this shape created on Matlab to an .stl file and I came across "surf2stl" in Mathworks File Exchange. (https://mathworks.com/matlabcentral/fileexchange/4512-surf2stl)
function out=fun2(x,y,z)
fun1=@(x,y,z) (x.^2 y.^2).^(2)-(x.^3 y.^3).*(z/4-z.^2).^(1/2);
dt=0.25*(z/4-z.^2).^(1/2); %z-dependent translation
out=fun1(x dt,y dt,z);
end
Meanwhile, a simple example of using the surf2stl would be:
x=linspace(0,2)
y=linspace(-pi,pi)
[X,Y] = meshgrid(x,y);
Z=sqrt(X).*cos(Y);
surf2stl('fun.stl', X, Y, Z);
The problem is that my code has an implicit function between X, Y, and Z, plus there's a z-dependent translation that moves the x and y coordinates, so it may be tricky to implement this function to surf2stl. I cannot figure out how to deal with the issue. Have any ideas?
(R2021a)
CodePudding user response:
Note that surf2stl
only works for parametrized surfaces that have been sampled on a regular rectangular grid. You can use stlwrite
instead. But to create a surface from an implicit function, we first need to sample the function on a grid (first creating the grid using meshgrid
), then call isosurface
. Then stlwrite
needs a triangulation object, which we can create using triangulation
.
% define function
fun1=@(x,y,z) (x.^2 y.^2).^2-(x.^3 y.^3).*(z/4-z.^2).^(1/2);
dt=@(z)0.25*(z/4-z.^2).^(1/2);
helper=@(x,y,z,dt)fun1(x dt, y dt, z);
fun=@(x,y,z)helper(x,y,z,dt(z));
% code
[x,y,z] = meshgrid(linspace(-3, 3, 40));
v = fun(x,y,z);
v = real(v); % deal with complex values
[faces, verts] = isosurface(x,y,z,v,0);
t = triangulation(faces, verts);
stlwrite(t, 'test.stl');
disp('done');