I have trajectory information in 3 dimensions in matlab. These are of a gesture someone is making. When I connect the points in matlab by using plot3, I can see the trajectory nicely.
However, the trajectory is a line in the plot, but I don't know in which direction the gesture has been made as the time is not visualized. Is it possible to visualize this in a 3d plot (where the dimensions are x, y and z)? For example, the colour at the start is bright red and the colour at the end is black.
Thanks for your help,
Héctor
You need the comet3 plot (if you don't mind animations).
If you do mind animations, and you're looking for a static figure, I'd use a quiver.
Example:
% value of the parameter in the parametric equation
t = 0:0.5:2*pi;
% modified coordinate axes
u = [1 0 0].';
v = [0 2 0].';
% coordinates of the ellipse
Ell = bsxfun(#plus, bsxfun(#times, u, cos(t)), bsxfun(#times, v, sin(t)));
% difference vectors between all data points will be used as "velocities"
dEll = diff(Ell, 1,2);
% Quiver the ellipse
quiver3(...
Ell(1,1:end-1), Ell(2,1:end-1), Ell(3,1:end-1), ...
dEll(1,:), dEll(2,:), dEll(3,:), ...
2, 'r') % = scale, LineSpec
axis tight equal
Result:
Related
Getting right to the question: How can I make my plot go from looking like this:
to something like this:
where a right-handed Cartesian coordinate system (with axis labels at the end of the arrows, e.g., in this example the x-axis label is = $x_1^G$)
Some elaboration and prefacing: First, I am new to matlab and "matrix math". I tried searching on this site for questions similar to what I have posed above but did not see anything (but I may have missed), so hopefully this is not a duplicate.
Here is the code I have used to develop my rotated ellipsoid (since I'm new to matlab I would appreciate any comments on my code):
%Insert the components of the 3x3 matrix (i.e. the scalar values of the 2nd-rank symmetric tensor)
Pmatrix = [115.9547 12.03765 4.68235; 12.03765 116.3702 -2.47985; 4.68235 -2.47985 134.5488];
[R,D]=eig(Pmatrix); %find the eigenvectors (R) and eigenvalues (D) of the 2nd-rank tensor
[x, y, z] =sphere; %generate coordinates of a sphere, using the sphere command
%Stretch the coordinates of the sphere to form the tensor's representation ellipsoid, do this by multiplying the x, y, z coordinates by the square-roots of the eigenvalues
x1 = x*sqrt(D(1,1));
y1 = y*sqrt(D(2,2));
z1 = z*sqrt(D(3,3));
figure;
hmesh = mesh(x1,y1,z1);
set(hmesh,'FaceColor',[0.5,0.5,0.5],'FaceAlpha',0.5) %set color to gray, make mostly transparent
axis equal; %Make tick mark increments on all axes equal
xlabel('x');
ylabel('y');
zlabel('z');
theta1 = -asind(R(3,1)); %rotation around y-axis in degrees
psi1 = atan2d(R(3,2)/cos(theta1),R(3,3)/cos(theta1)); %rotation around x-axis in degrees
phi1 = atan2d(R(2,1)/cos(theta1),R(1,1)/cos(theta1)); %rotation around z-axis in degress
direction = [1 0 0]; %rotate the surface plot psi1 degrees around its x-axis
rotate(hmesh,direction,psi1)
direction = [0 1 0]; %rotate the surface plot theta1 degrees around its y-axis
rotate(hmesh,direction,theta1)
direction = [0 0 1]; %rotate the surface plot phi1 degrees around its z-axis
rotate(hmesh,direction,phi1)
view([-36 18]); %Change the camera viewpoint
To add to my question, I would like to add other (similar) items to my plot, so that the final product would look like this:
In the development of the image above, a set of axes collinear with the ellipsoid's eigenvectors are added (the red, green, blue arrows):
Then these axes are extended in the opposite direction, through the origin, where these portions of the axes are shown as a dashed lines:
Then, the angles between the global coordinate axes (black arrows) and the ellipsoid's axes (colored arrows) are notated as shown here:
To comment on this last addition, someone has built some matlab code with these features (see youtube video here). In the video's description it says the matlab code can be found here. Being new to matlab, I don't see where the code is, e.g., I don't see where on this page (screenshot below) the code is to build that matlab plot seen in the youtube video. If you can guide me on how to navigate that mathworks-fileexchage page that would be appreciated.
I am working on creating 3D images from 3 individual binary images, that were taken with 3 cameras. I have a corresponding calibration and know the setup (see below). Since the image preprocessing is mostly done in MATLAB I would like to implement everything there.
The current idea of my code is to extrude the 2D binary image according to the camera calibration. Here's what a typical binary image looks like:
And an extruded image looks like this in MATLAB:
With all 3 cameras extruded and a binning algorithm, I can create my final 3D-shape. This works fine so far, but takes a long time to compute, since I need to create a lot of extrusion steps to get a good surface.
I was thinking now to speed this up by recreating the process I would do in a 3D-modeling software like Blender. There I also extrude the outline of the binary image and create an intersection easily by just creating a spline for the outline, extrude them and use a boolean operator. Here's a Blender example with 2 extruded images:
I have no idea how to implement something like this in MATLAB. I wanted to create two instances of my binary contour at the top and bottom end of the extrusion "tube" and then define faces between the individual points and create an intersection afterwards. The point creation is no problem but the face definition and the intersection (boolean operator) are. Does anyone have an idea how this could be implemented?
This might not be an easy thing to do in MATLAB, but it's possible. I'll outline one set of steps here, using two intersecting cylinders as an example...
Creating a tetrahedral mesh:
The first step is to create a tetrahedral mesh for your extrusion. If your 2D binary image that you're extruding is convex and has no holes, you could do this using the delaunayTriangulation function:
DT = delaunayTriangulation(P);
Here, P contains the coordinate points of the "end caps" of your extrusion (i.e. the faces on each end of your tube). However, when generating tetrahedral meshes, delaunayTriangulation doesn't allow you to specify constrained edges, and as such it can end up filling in holes or concavities in your extrusion. There may be some better mesh-generation alternatives in other toolboxes, such as the Partial Differential Equations Toolbox, but I don't have access to them and can't speak to their applicability.
If automated mesh-generation options don't work, you'll have to build your tetrahedral mesh yourself and pass that data to triangulation. This could be tricky, but I'll show you some steps for how you can do this for a cylinder, which may help you figure it out for more involved shapes. Below, we build a set of coordinate points P1 and an M-by-4 matrix T1 where each row contains indices into the rows of P1 which define one tetrahedron:
% Create circle coordinates for the end caps:
N = 21;
theta = linspace(0, 2*pi, N).';
x = sin(theta(1:(end-1)));
y = cos(theta(1:(end-1)))+0.5;
z = ones(N-1, 1);
% Build tetrahedrons for first cylinder, aligned along the z axis:
P1 = [0 0.5 -1; ... % Center point of bottom face
x y -z; ... % Edge coordinates of bottom face
0 0.5 1; ... % Center point of top face
x y z]; % Edge coordinates of top face
cBottom = ones(N-1, 1); % Row indices for bottom center coordinate
cEdgeBottom1 = (2:N).'; % Row indices for bottom edge coordinates
cEdgeBottom2 = [3:N 2].'; % Shifted row indices for bottom edge coordinates
cTop = cBottom+N; % Row indices for top center coordinate
cEdgeTop1 = cEdgeBottom1+N; % Row indices for top edge coordinates
cEdgeTop2 = cEdgeBottom2+N; % Shifted row indices for top edge coordinates
% There are 3 tetrahedrons per radial slice of the cylinder: one that includes the
% bottom face and half of the side face (all generated simultaneously by the first row
% below), one that includes the other half of the side face (second row below), and one
% that includes the top face (third row below):
T1 = [cEdgeBottom1 cEdgeBottom2 cEdgeTop1 cBottom; ...
cEdgeBottom2 cEdgeTop1 cEdgeTop2 cBottom; ...
cEdgeTop1 cEdgeTop2 cTop cBottom];
TR1 = triangulation(T1, P1);
To better visualize how the cylinder is being divided into tetrahedrons, here's an animation of an exploded view:
Now we can create a second cylinder, offset and rotated so it aligns with the x axis and intersecting the first:
% Build tetrahedrons for second cylinder:
P2 = [P1(:, 3) -P1(:, 2) P1(:, 1)];
T2 = T1;
TR2 = triangulation(T2, P2);
% Plot cylinders:
tetramesh(TR1, 'FaceColor', 'r', 'FaceAlpha', 0.6);
hold on;
tetramesh(TR2, 'FaceColor', 'g', 'FaceAlpha', 0.6);
axis equal;
xlabel('x');
ylabel('y');
zlabel('z');
And here's the plot to visualize them:
Finding the region of intersection:
Once we have tetrahedral representations of the volumes, we can generate a grid of points covering the region of intersection and use the pointLocation function to determine which points are within both cylinders:
nGrid = 101;
[X, Y, Z] = meshgrid(linspace(-1, 1, nGrid));
QP = [X(:) Y(:) Z(:)];
indexIntersect = (~isnan(pointLocation(TR1, QP))) & ...
(~isnan(pointLocation(TR2, QP)));
mask = double(reshape(indexIntersect, [nGrid nGrid nGrid]));
We now have volume data mask that contains zeroes and ones, with the ones defining the region of intersection. The finer you make your grid (by adjusting nGrid), the more accurately this will represent the true region of intersection between the cylinders.
Generating a 3D surface:
You may want to create a surface from this data, defining the boundary of the intersection region. There are a couple ways to do this. One is to generate the surface with isosurface, which you could then visualize using featureEdges. For example:
[F, V] = isosurface(mask, 0.5);
TR = triangulation(F, V);
FE = featureEdges(TR, pi/6).';
xV = V(:, 1);
yV = V(:, 2);
zV = V(:, 3);
trisurf(TR, 'FaceColor', 'c', 'FaceAlpha', 0.8, 'EdgeColor', 'none');
axis equal;
xlabel('x');
ylabel('y');
zlabel('z');
hold on;
plot3(xV(FE), yV(FE), zV(FE), 'k');
And the resulting plot:
Another option is to create a "voxelated" Minecraft-like surface, as I illustrate here:
[X, Y, Z, C] = build_voxels(permute(mask, [2 1 3]));
hSurface = patch(X, Y, Z, 'c', ...
'AmbientStrength', 0.5, ...
'BackFaceLighting', 'unlit', ...
'EdgeColor', 'none', ...
'FaceLighting', 'flat');
axis equal;
view(-37.5, 30);
set(gca, 'XLim', [0 101], 'YLim', [25 75], 'ZLim', [0 102]);
xlabel('x');
ylabel('y');
zlabel('z');
grid on;
light('Position', get(gca, 'CameraPosition'), 'Style', 'local');
And the resulting plot:
I have two datasets. One detailing a list of angles (which I am plotting onto a rose plot):
angles
-0.8481065519
0.0367932161
2.6273740453
...
n
The other, detailing directional statistics from this group of angles:
angle,error
-0.848106563,0.8452778824
Where angle essentially defines the directional mean, and error the circular variance, essentially an error bar either side of the angle
I have thus far plotted a rose histogram using the set of angles, as such:
h = rose(angles,36)
I would like to create a plot of the directional statistic angle (it does not need a length/magnitude - just to the edge of the circle plot) with the error around it.
As an example:
I added the lines by hand in Matlab. If possible it would be good to perhaps have shading within the arc too. Alternatively, (and possibly preferred) would be to have just a sliver above the rose plot bins (so it doesn't cover the data) with a centre line (showing the angle and shading surrounding for the error.
Thanks in advance.
How about this?
%// Data
angles = 2*pi*.8*randn(1,1e4);
angle = -0.848106563;
error = 0.8452778824;
%// Plot rose
rose(angles, 36);
axis image %// make axis square
hold on
%// Plot mean
a = axis;
a = a(2); %// size of axis
plot([0 cos(angle)*a], [0 sin(angle)*a], 'r')
%// Plot error as many shaded triangles that compose a circular wedge
t = linspace(-error/2+angle,error/2+angle,100); %// increase "100" if needed
for k = 1:numel(t)-1
h = patch([0 cos(t(k))*a cos(t(k+1))*a 0], ...
[0 sin(t(k))*a sin(t(k+1))*a 0], [.5 0 0], 'edgecolor', 'none');
%// change color [.5 0 0] to something else if desired. Note also alpha
set(h,'Facealpha',.3) %// make transparent
end
%// Place rose on top by rearranging order of axis children
ch = get(gca,'children');
set(gca,'children',[ch(2:end); ch(1)]);
For this to work, you need to use a figure renderer capable of transparency. So you may need to adjust the figure's renderer property.
I'm working on a project which includes use of accelerometer and gyroscope to get the orientation an object. I can pass the 3d orientation vector from arduino to matlab via serial communication.
I want to plot the vector in matlab to make real time analysis. I'm using quiver3d and drawnow functions in a loop to plot the vector but quiver3d function is very slow so I can see the orientation of object after like 20 seconds later.
Is there any way to plot 3d vectors faster?
Thanks.
quiver plot may be too much for plotting only one vector in 3-D. You can achieve a similar plot by using a simple plot3 such as the one plotted below.
In this plot, the origin of the vector is the blue dot, and the direction is given by the red line.
The code
%v is the direction of the vector (3 cartesian coordinates)
v = sort(randn(100,3));
v = bsxfun(#rdivide,v,sqrt(sum(v.^2,2)));
%xyz the origin of the vector
ind = linspace(-pi,pi,100);
x = cos(ind);
y = sin(ind);
z = ind;
%the plotting function
figure
for ii = 1:numel(ind)
plot3(x(ii),y(ii),z(ii),'bo'); %origin in blue
set(gca,'XLim', [-3 3], 'YLim', [-3 3], 'ZLim', [-3 3]);
hold on;
hl = plot3( linspace(x(ii), x(ii)+v(ii,1),10), ...
linspace(y(ii), y(ii)+v(ii,2),10), ...
linspace(z(ii), z(ii)+v(ii,3),10), ...
'r'); %direction in red
view(80,10);
pause(0.1);
%clf
end
I am working in MATLAB and I'm stuck on a very simple problem: I've got an object defined by its position (x,y) and theta (an angle, in degrees). I would like to plot the point and add an arrow, starting from the point and pointing toward the direction defined by the angle. It actually doesn't even have to be an arrow, anything graphically showing the value of the angle will do!
Here's a picture showing the kind of thing I'm trying to draw:
removed dead ImageShack link
The quiver() plotting function plots arrows like this. Take your theta value and convert it to (x,y) cartesian coordinates representing the vector you want to plot as an arrow and use those as the (u,v) parameters to quiver().
theta = pi/9;
r = 3; % magnitude (length) of arrow to plot
x = 4; y = 5;
u = r * cos(theta); % convert polar (theta,r) to cartesian
v = r * sin(theta);
h = quiver(x,y,u,v);
set(gca, 'XLim', [1 10], 'YLim', [1 10]);
Take a look through online the Matlab documentation to see other plot types; there's a lot, including several radial plots. They're in the MATLAB > Functions > Graphics > Specialized Plotting section. Do "doc quiver" at the command line and browse around.
If you want to try and make something that looks like the image you linked to, here's some code to help you do it (NOTE: you would first have to download the submission arrow.m by Erik Johnson on the MathWorks File Exchange, which I always like to use for generating arrows of any shape and size):
x = 1; % X coordinate of arrow start
y = 2; % Y coordinate of arrow start
theta = pi/4; % Angle of arrow, from x-axis
L = 2; % Length of arrow
xEnd = x+L*cos(theta); % X coordinate of arrow end
yEnd = y+L*sin(theta); % Y coordinate of arrow end
points = linspace(0, theta); % 100 points from 0 to theta
xCurve = x+(L/2).*cos(points); % X coordinates of curve
yCurve = y+(L/2).*sin(points); % Y coordinates of curve
plot(x+[-L L], [y y], '--k'); % Plot dashed line
hold on; % Add subsequent plots to the current axes
axis([x+[-L L] y+[-L L]]); % Set axis limits
axis equal; % Make tick increments of each axis equal
arrow([x y], [xEnd yEnd]); % Plot arrow
plot(xCurve, yCurve, '-k'); % Plot curve
plot(x, y, 'o', 'MarkerEdgeColor', 'k', 'MarkerFaceColor', 'w'); % Plot point
And here's what it would look like:
You can then add text to the plot (for the angle and the coordinate values) using the text function.
Here's a partial answer, I expect you can figure out the rest. I fired up the Figures editor and opened the plot tools. I dragged an arrow from the palette onto my figure. Then I generated an m-file. This included the line:
annotation(figure1,'arrow',[0.1489 0.2945],[0.5793 0.6481]);
So, the first pair of coordinates is the start of the arrow. You're going to have to figure out the pointy end (second pair of coordinates) using a little bit of trigonometry. You might even be able to get the little arc if you do some more fiddling around with plot tools.
Let us know if the trig defeats you. Oh, and I forgot to plot the point, but I guess you can figure that out ?