How to overlap a point cloud file with another plot in Matlab? - 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

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):

Get a plot like spectrogram in MATLAB

I would like to get a plot of the same type of the one that I get with spectrogram function, I am trying with contour but I do not get the same result. I have written a small function which compares the two plot. The function records audio for one second and then plot the spectrogram.
function graph_comparison
a = audiorecorder(44100,16,1);
recordblocking(a,1);
y = getaudiodata(a);
figure
subplot(1,2,1);
spectrogram(y);
s = spectrogram(y);
subplot(1,2,2);
contour(mag2db(abs(s))); %mag2db converts intensity in db
%rotate the second plot
view(-90, 90);
set(gca, 'ydir', 'reverse');
end
Example of plot result:
I found it, it is sufficient to replace contour with imagesc.

How to export mesh in MATLAB to stl or obj?

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);

How to add a regression line to a scatter plot in MATLAB

I am trying to add a regression line onto a plot in MATLAB.
this is the code I have:
errorbar(x,y,SEM,'o')
hold on % Retains current plot while adding to it
scatter(x,y)
title('The Effect of Distance Between Images on the Flashed Face Distortion Effect','FontSize',14); % Adds title
xlabel('Distance (Pixels)','FontSize',12); % Adds label on the x axis
ylabel('Average Distortion Rating','FontSize',12); % Adds label on the y axis
hold off
And this is my code for a regression:
mdl = fitlm(x,y,'linear');
Could anyone tell me how to combine the two so i get the regression line on the plot?
I am using psychtoolbox on MATLAB on Windows.
Thanks!
Before the hold off statement, add the following lines:
xf = [min(x), max(x)];
plot(xf, polyval(polyfit(x,y,1), xf));
You may want to decorate your plot call with supplemental arguments setting the line style, and no additional toolboxes are required.

Create 2D Spectrogram in Matlab

I am in need of plotting a 2D spectrogram of a signal in Matlab. I need it for a printed assignment, hence the 3D image makes no sense. However, when the signal is plotted using Spectrogram it automatically produces a 3D plot of the signal.
My Code:
Dataset = 1; % Dataset to be analysed
N = 1024; % Window size
Beta = 12; % Kaiser window beta value (small = narrow main lope)
Overlap = 800; % Window overlap
Threshold = -150; % Minimum magnitude before threshold
spectrogram(Enclosure{Dataset}(1:end),kaiser(N,Beta),Overlap,2048,fs,'MinThreshold',Threshold,'yaxis');
which produces a graph that looks like this:
But it is seen from the top, and the graph is really showing this:
The reason why i need it to specifically be 2D (and why i don't settle with a screenshot) is because i am using Matlab2tikz to convert Matlab figures into Tikz figures in LaTex. with the 3D images i get figures of +100 Mb and 2D will reduce the size to <1Mb.
I don't know what version of Matlab you are using but in 2015a you should be able to get a handle to the figure with the 3D plot and change the view angle to 2D:
view(0,90);
I've also got an example of how you can make your own 2D plot from the outputs of spectrogram() using a similar method:
x = [0:0.01:100];
y = sin(5*x);
y = awgn(y,0.1);
[S,F,T,P] = spectrogram(y,200,0,length(y)*5,100);
[m,n] = size(P);
figure(2)
surf(F,T,zeros(n,m),P','EdgeColor','none')
view(0,90)
xlabel('Frequency')
ylabel('Time (s)')
The output looks like this:
Hopefully since there is no altitude information, the figure size might be smaller but I can't test that since I don't have Matlab2tikz.
One option is to capture whatever its plotted and then plot it as an image. You can do this using getframe
if you do
F=getframe(gca);
cla;
imshow(F.cdata);
You'll get exactly what you will be seeing before, but as an image.
However I think it defeats a bit the purpose of Matlab2Tikz, as the idea os that you have Tikz code describing your data...
You can try the following:
[~,F,T,ps]=spectrogram(Enclosure{Dataset}(1:end),kaiser(N,Beta),Overlap,2048,fs,'MinThreshold',Threshold,'yaxis').
% Output the spectrum in ps
imagesc(T,F,10*log10(ps))
% Generate a 2d image
view(270,90)
xlabel('Time [s]')
ylabel('Frequency [Hz]')
c=colorbar;
c.Label.String='Power [dB]';
% Extra setting to make the plot look like the spectrogram
Good luck