How to export mesh in MATLAB to stl or obj? - matlab

I have written MATLAB code (shown below) which makes an edge and then builds mesh extending from that edge. I can see the 3D model in a figure as a mesh, but there is no way to export this model as a 3d object such as an stl or obj.
I read many examples of converting to stl, which used something like this:
% Extract the surface mesh
M=isosurface(x,y,z,F,0);
tr=TriRep(M.faces,M.vertices);
figure('color','w'), h=trimesh(tr); axis equal
% Write to .stl
stlwrite('PillBoxExample.stl',tr.Triangulation,tr.X)
But in my code I used just mesh:
figure;
M= surface(-finalLSF);
hold on; contour(phi, [0,0], 'r','LineWidth',2);
I tried many time to convert it but am still having errors.
Code:
Img = imread('MK2.jpg');
Img=double(Img(:,:,1));
%
% ... other code ...
%
figure;
M= mesh(-finalLSF);
hold on; contour(phi, [0,0], 'r','LineWidth',2);
str=['Final level set function, ', num2str(iter_outer*iter_inner+iter_refine), ' iterations'];
title(str);
axis on;

For using stlwrite you need the source code of it. Matlab doesnt have the feature.
https://de.mathworks.com/matlabcentral/fileexchange/20922-stlwrite-filename--varargin- should do it.

You need to download stlwrite from File Exchange, and put it within your Matlab path. You can check if it is on your path by typing exist('stlwrite'). If this returns 2, you're good. If it returns 0 then you need to add it to your path.
It seems like you have the x,y and z coordinates, in which case you can just call
stlwrite('C:\...\filename.stl', x, y, z);
If you wanted to use isosurface first, then just use
M = isosurface(x,y,z,F,0);
stlwrite('C:\...\filename.stl', M);

Related

line passing through a triangulated mesh (MatLab)

I have a triangulated mesh (as in the figure) and I would like to found the line passing trhough the points (see figure). i tried by a 2D fit but I lose the shape of the mesh.
Can someone suggest a method to obtain a line as that I drown by hand?
Without an actual 3D path or mesh to work with, I have simulated one and show you how to use 3D splines for interpolation:
% simulating a 3D path and plotting it
N = 1000;
rng(1);
xyz = cumsum([randn(N,1)+0.8, randn(N,1)+0.2, randn(N,1)*2]);
plot3(xyz(:,1),xyz(:,2),xyz(:,3),'-b','LineWidth',2);
box on; view(30,30);
% interpolating using 3D splines.
% "smoothness" determines how many points to skip.
smoothness = floor( N/30 );
hold on;
fnplt(cscvn(xyz(1:smoothness:end,:)'),'r',2);
hold off;
Here is what the result shows (the original path is blue, the interpolated path is red):

How to overlap a point cloud file with another plot in Matlab?

I have a .pcd file of a terrain survey that I opened using this command:
% read point cloud
big_island_cloud = pcread('C:\Users\to\path\Desktop\big_island_5m.pcd');
pcshow(big_island_cloud)
Now I read from a .csv file all necessary columns using readtable in the following way and and verify that everything is fine file(1:3,:) and plot the result using stackedplot:
file = readtable('C:\Users\to\path\Desktop\EKF_USBL_CAM_Pose_Projected.csv');
file(1:3,:)
timeStamp = file(:,1);
pose_pose_position_x = file(:,4);
pose_pose_position_y = file(:,5);
stackedplot(file,{'time','field_pose_pose_position_x'});
and the following is what I obtain, pose_pose_position_x is going to be the trajectory I have to draw on top of the .pcd file:
How do I obtain the following output?:
Thank you for shedding light on this matter
Supposing that you have [x,y,z] for the data of your trajectories then you can simply superpose a plot with the use of hold on and plot3:
Based on the example in the MATLAB documentation :
numFaces = 600;
[x,y,z] = sphere(numFaces);
figure;
pcshow([x(:),y(:),z(:)]);hold on % keeps the first plot on screen
plot3([1,1,-1],[1,0.5,1],[1,-0.5,-1]) % adds the trajectory on the plot
title('Sphere with Default Color Map');
xlabel('X');
ylabel('Y');
zlabel('Z');
Result
Edit
If you only have [x,y] then plot will replace plot3
plot([1,1,-1],[1,0.5,1]) % adds the trajectory on the plot
Note that the trajectory will be drawn on the plane with z=0

Using streamslice with color for velocities

I am using streamslice command to visualize my flow. I want to add color depending on magnitude of velocities but there seems to be no function argument in streamslice to do so. The function is given as:
% x - x-coordinates
% y - y-coordinates
% u,v - vector volume data
h = streamslice(x,y,u,v)
The function produces this image
If you want to use streamslice, I can suggest something. It would need some tweaking to get it look like a cool figure, but it does the job, I guess. the idea is to combine a surf plot with the streamsilces plot.
Look at the result. I guess that with better a colormap and with some tricks getting the data handle of the streamsliceto change the line colour it could work nicely, speciall yin Matlab R2014b or higher.
CODE:
clear;clc;
load wind
% Use only a piece of this datasheet
x=x(:,:,5);
y=y(:,:,5);
u=u(:,:,5);
v=v(:,:,5);
mag=sqrt(u.^2+v.^2);
figure
hold on
surf(x,y,mag-max(mag(:)),'FaceColor','interp','Edgecolor','none')
colormap('hot')
streamslice(x,y,u,v)
axis([min(x(:)) max(x(:)) min(y(:)) max(y(:)) -max(mag(:)) 0])

MATLAB - fill ezpolar plot

I just have a brief question regarding MatLab.
Say that we have the equation:
r^2 = 2 sin(5t)
I know that I can fill a polar plot by writing, say:
t = linspace(0,2*pi,200);
r = sqrt(abs(2*sin(5*t)));
x = r.*cos(t);
y = r.*sin(t);
fill(x,y,'k')
But say I use the ezpolar instead by giving the equation above a function handle and then typing:
ezpolar(function handle)
Is there any way I can then fill this polar plot? Or do I have to use the procedure outlined above?
Any tips/help will be greatly appreciated!
You can use ezpolar, then modify the resulting figure. If you look at the returned handle from ezpolar, you'll see it is the line itself drawn in the axis. The points from that line object can be extracted, then used to lay a new polygon on top of the same axis. The benefit is, you get to keep all the nice polar lables.
h=ezpolar('sqrt(abs(2*sin(5*t)))')
hold on;
fill(get(h, 'XData'), get(h, 'YData'), 'k');

Matlab: Plot3 not showing the 3rd axis

All the three variables I am using to plot are matrix of size 1x1x100. I am using this code line to plot:
hold on;
for i=1:100
plot3(R_L(:,:,i),N_Pc(:,:,i),CO2_molefraction_top_of_window(:,:,i),'o');
xlabel('R_L');
ylabel('N_P_c');
zlabel('CO_2')
end
However, I am not getting the third axis, and hence the third variable CO2_molefraction_top_of_window on the plot. May I know where am I wrong?
Besides the above question, but on the same subject, I want to know if there is any option where I can plot 4 dimensional plot just like the 3 dimensional plot which can be drawn using plot3?
So I had the same problem when using plot3. For some reason, using the hold on command "flattens" the plot. I'm not sure why, but I suspect it has something to do with the operation hold on performs on the plot.
Edit: To clarify, the 3d plot is still there, but the perspective has been forced to change. If you use the "rotate 3D" tool (the one with an arrow around a cube), you can see the graph is 3d, the default perspective is just straight on so only two axes are visible and it appears flat.
Just a note --- you only need to do the xlabel ylabel zlabel commands once (outside the loop).
Also:
is there any reason your matrices are 1x1x100 instead of just 100x1 or 1x100?
Because if you reshape them to 2D you can just do the plotting in one hit.
What do you mean by "missing third axis"? When I run your code (or as close as I can get, since you didn't provide a reproducible example), I do get a 3rd axis:
.
X = rand(1,1,100); % 1x1x100 X matrix
Y = rand(1,1,100); % 1x1x100 Y matrix
Z = rand(1,1,100); % 1x1x100 Z matrix
% Now, we could do a for loop and plot X(:,:,i), Y(:,:,i), Z(:,:,i),
% OR we can just convert the matrix to a vector (since it's 1x1x100 anyway)
% and do the plotting in one go using 'squeeze' (see 'help squeeze').
% squeeze(X) converts it from 1x1x100 (3D matrix) to 100x1 (vector):
plot3(squeeze(X),squeeze(Y),squeeze(Z),'o')
xlabel('x')
ylabel('y')
zlabel('z')
This gives the following, in which you can clearly see three axes:
If it's the gridlines that you want to make the graph look "more 3D", then try grid on (which is in the examples in the Matlab help file for plot3, try help plot3 from the Matlab prompt):
grid on
You will have to clarify "missing third axis" a bit more.
I came across a similar problem and as #Drofdarb's the hold on seems to flatten out one axis. Here is a snippet of my code, hope this helps.
for iter = 1:num_iters:
% hold on;
grid on;
plot3(tita0,tita1, num_iters,'o')
title('Tita0, Tita1')
xlabel('Tita0')
ylabel('Tita1')
zlabel('Iterations')
hold on; % <---- Place here
drawnow
end
As opposed to:
for iter = 1:num_iters:
grid on;
hold on; % <---- Not here
plot3(tita0,tita1, num_iters,'o')
title('Tita0, Tita1')
xlabel('Tita0')
ylabel('Tita1')
zlabel('Iterations')
% hold on;
drawnow
end