Adjust projection of 3d plot in Matlab - matlab

Matlab doesn't have an easy off-the-shelf way to adjust the distortion of the projection's perspective of a 3D figure that I know of. So, given the code below:
figure;
x1 = rand(1,10);
x2 = rand(1,10);
x3 = rand(1,10);
scatter3(x1,x2,x3,80,'o','filled'); hold on
ax = gca;
ax.Projection='perspective';
the results is unimpressive:
I tried modifying ax.CameraTarget, the ax.CameraPosition, etc. but the it's nearly impossible to modify the "vanishing point" to look more distorted, e.g. like this:
Any help as to how to achieve this level of control on the figure appearance?
thanks!

You can achieve this by moving into the "wide angle" regime, i.e. choosing a large CameraViewAngle while moving the camera further towards the plot. That gives you quite some distortion, like you might know from wide angle camera lenses.
In the following code, I assumed that the camera is placed at the center z-level of the coordinate system and x and y-coordinates are displaced just at the connection line between two edge points of the coordinate system being back-shifted by its length. The rest is basically "law of cosines". Feel free to adapt the camera position within the given sensible levels, such that the view angle remains in the range between 0 and 180 degrees, https://de.mathworks.com/help/matlab/ref/matlab.graphics.axis.axes-properties.html#budumk7-View). This example assumes that the view angle in the x-y-plane is about the same as in the y-z-plane. Otherwise one would need to extend the calculation and take the average or maximum angle of both.
figure;
x1 = rand(1, 10) + 10;
x2 = rand(1, 10) + 15;
x3 = rand(1, 10) + 10;
scatter3(x1, x2, x3, 80, 'o', 'filled');
% get the axis limits
xax = xlim; yax = ylim; zax = zlim;
ax = gca;
ax.Projection = 'perspective';
% get the default camera target (where the cam looks at)
camTarget = get(ax, 'CameraTarget');
newCamPos = [ 2*xax(1)-xax(2) 2*yax(1)-yax(2) camTarget(3) ];
a = sqrt((xax(1)-newCamPos(1))^2 + (yax(2)-newCamPos(2))^2);
b = sqrt((xax(2)-newCamPos(1))^2 + (yax(1)-newCamPos(2))^2);
lsqr = (xax(2)-xax(1))^2 + (yax(2)-yax(1))^2;
angle = acos((lsqr - a^2 - b^2) / -(2*a*b)) *180/pi;
set(ax, 'CameraViewAngle', angle, ...
'CameraPosition', newCamPos);

Related

How to move the figure viewpoint to a 3d position, looking along a vector?

I am plotting a 3d point cloud, but am having difficulty rotating the figure into a certain pose.
For example,
figure; hold on;
z = linspace(0,3*pi,250);
x = 2*cos(z) + rand(1,250);
y = 2*sin(z) + rand(1,250);
plot3(x, y, z, 'b.', 'MarkerSize', 20);
plot3(x(1), y(1), z(1), 'kx', 'MarkerSize', 20);
plot3([x(1) x(end)], [y(1) y(end)], [z(1) z(end)], '-k');
The default perspective is
I want to look along the black line from the 'X' position. I can manually rotate the figure with the GUI controls, and I find that I get closest at Azimuth 96 Elevation -46
I can rotate the view to this position using
view(96, -46);
However, the viewpoint isn't actually positioned on top of the 'X'. 'X' is some distance in front of the viewpoint. Additionally, I have a different vector every time I call this code, so I can't use the same azimuth and elevation every time.
I should be able to calculate the azimuth and elevation from the vector. My attempt,
x_dif = x(end)- x(1);
y_dif = y(end)-y(1);
z_dif = z(end)-z(1);
azimuth = (atan(x_dif/y_dif))*180/pi;
elevation = (atan(z_dif/sqrt(x_dif^2+y_dif^2)))*180/pi;
view(azimuth, elevation);
This produces an incorrect solution. I think it may be because the azimuth and elevation should be relative to the center of the plot box. (view documentation). I'm not sure how to do this.
How can I calculate and apply a rotation to the figure given the vector?
view has an option to use a cartisian direction [x,y,z] rather than [alt,azi].
This works for me: (Please note the axis equal call to avoid deformations in the default plot axis scaling)
function cecilia()
figure; hold on;
z = linspace(0,3*pi,250);
x = 2*cos(z) + rand(1,250);
y = 2*sin(z) + rand(1,250);
plot3(x, y, z, 'b.', 'MarkerSize', 20);
plot3(x(1), y(1), z(1), 'kx', 'MarkerSize', 20);
plot3([x(1) x(end)], [y(1) y(end)], [z(1) z(end)], '-k');
x_dif = x(end)- x(1);
y_dif = y(end)-y(1);
z_dif = z(end)-z(1);
view([x_dif,y_dif,z_dif]);
axis equal
end
You should see the following result:
Enjoy!

matlab: moving circle along a graph and axis equal

Hello and pardon me if my english is a bit rusty. I'm trying to create a circle that moves along a parametric function (coordinates are stored in vectors). I have written a function for drawing the circle and I know that you can use the axis equal command in matlab in order to create a circle shape and avoid an ellipse. My problem is that when I do this the figure window becomes very wide relative to the plotted graph. Any input is appreciated.
MAIN CODE:
t = linspace(0,3);
x = 30*cos(pi/4)/2*(1-exp(-0.5*t));
y = (30*sin(pi/4)/2 + 9.81/0.5^2)*(1-exp(0.5*t)) - 9.81*t/0.5;
for i = 1:length(t)
plot(x,y)
axis equal
hold on
cirkel(x(i),y(i),1,1,'r') % argument #3 is the radius #4 is 1 for fill
hold off
pause(0.01)
end
CIRCLE CODE:
function cirkel(x,y,r,f,c)
angle = linspace(0, 2*pi, 360);
xp = x + r*cos(angle);
yp = y + r*sin(angle);
plot(x,y)
if f == 1 && nargin == 5
fill(xp,yp,c)
end
When you call axis equal it makes one unit of the x axis be the same size as one unit of the y axis. You are seeing what you are because your y values span a much larger range than the x values.
One way to deal with this would be to query the aspect ratio and x/y limits of the current axes as shown in the second part of this answer. However, an easier approach is rather than using fill to plot your circle, you could instead use scatter with a circular marker which will be circular regardless of the aspect ratio of your axes.
t = linspace(0,3);
x = 30*cos(pi/4)/2*(1-exp(-0.5*t));
y = (30*sin(pi/4)/2 + 9.81/0.5^2)*(1-exp(0.5*t)) - 9.81*t/0.5;
% Plot the entire curve
hplot = plot(x, y);
hold on;
% Create a scatter plot where the area of the marker is 50. Store the handle to the plot
% in the variable hscatter so we can update the position inside of the loop
hscatter = scatter(x(1), y(1), 50, 'r', 'MarkerFaceColor', 'r');
for k = 1:length(t)
% Update the location of the scatter plot
set(hscatter, 'XData', x(k), ... % Set the X Position of the circle to x(k)
'YData', y(k)) % Set the Y Position of the circle to y(k)
% Refresh the plot
drawnow
end
As a side note, it is best to update existing plot objects rather than creating new ones.
If you want the small dot to appear circular, and you want to have a reasonable domain (x-axis extent), try this:
function cirkel(x,y,r,f,c)
angle = linspace(0, 2*pi, 360);
xp = x + 0.04*r*cos(angle); %% adding scale factor of 0.04 to make it appear circular
yp = y + r*sin(angle);
plot(x,y)
if f == 1 && nargin == 5
fill(xp,yp,c)
end
Note the addition of the scale factor in the computation of xp. If you want to automate this, you can add another parameter to cirkel(), let's call it s, that contains the scale factor. You can calculate the scale factor in your script by computing the ratio of the range to the domain (y extent divided by x extent).

Matlab - Subtracting two 3D figures with surf and min function

I'm trying to make a surf plot that looks like:
So far I have:
x = [-1:1/100:1];
y = [-1:1/100:1];
[X,Y] = meshgrid(x,y);
Triangle1 = -abs(X) + 1.5;
Triangle2 = -abs(Y) + 1.5;
Z = min(Triangle1, Triangle2);
surf(X,Y,Z);
shading flat
colormap winter;
hold on;
[X,Y,Z] = sphere();
Sphere = surf(X, Y, Z + 1.5 );% sphere with radius 1 centred at (0,0,1.5)
hold off;
This code produces a graph that looks like :
A pyramid with square base ([-1,1]x[-1,1]) and vertex at height c = 1.5 above the origin (0,0) is erected.
The top of the pyramid is hollowed out by removing the portion of it that falls within a sphere of radius r=1 centered at the vertex.
So I need to keep the part of the surface of the sphere that is inside the pyramid and delete the rest. Note that the y axis in each plot is different, that's why the second plot looks condensed a bit. Yes there is a pyramid going into the sphere which is hard to see from that angle.
I will use viewing angles of 70 (azimuth) and 35 (elevation). And make sure the axes are properly scaled (as shown). I will use the AXIS TIGHT option to get the proper dimensions after the removal of the appropriate surface of the sphere.
Here is my humble suggestion:
N = 400; % resolution
x = linspace(-1,1,N);
y = linspace(-1,1,N);
[X,Y] = meshgrid(x,y);
Triangle1 = -abs(X)+1.5 ;
Triangle2 = -abs(Y)+1.5 ;
Z = min(Triangle1, Triangle2);
Trig = alphaShape(X(:),Y(:),Z(:),2);
[Xs,Ys,Zs] = sphere(N-1);
Sphere = alphaShape(Xs(:),Ys(:),Zs(:)+2,2);
% get all the points from the pyramid that are within the sphere:
inSphere = inShape(Sphere,X(:),Y(:),Z(:));
Zt = Z;
Zt(inSphere) = nan; % remove the points in the sphere
surf(X,Y,Zt)
shading interp
view(70,35)
axis tight
I use alphaShape object to remove all unwanted points from the pyramid and then plot it without them:
I know, it's not perfect, as you don't see the bottom of the circle within the pyramid, but all my tries to achieve this have failed. My basic idea was plotting them together like this:
hold on;
Zc = Zs;
inTrig = inShape(Trig,Xs(:),Ys(:),Zs(:)+1.5);
Zc(~inTrig) = nan;
surf(Xs,Ys,Zc+1.5)
hold off
But the result is not so good, as you can't really see the circle within the pyramid.
Anyway, I post this here as it might give you a direction to work on.
An alternative to EBH's method.
A general algorithm from subtracting two shapes in 3d is difficult in MATLAB. If instead you remember that the equation for a sphere with radius r centered at (x0,y0,z0) is
r^2 = (x-x0)^2 + (y-y0)^2 + (z-z0)^2
Then solving for z gives z = z0 +/- sqrt(r^2-(x-x0)^2-(y-y0)^2) where using + in front of the square root gives the top of the sphere and - gives the bottom. In this case we are only interested in the bottom of the sphere. To get the final surface we simply take the minimum z between the pyramid and the half-sphere.
Note that the domain of the half-sphere is defined by the filled circle r^2-(x-x0)^2-(y-y0)^2 >= 0. We define any terms outside the domain as infinity so that they are ignored when the minimum is taken.
N = 400; % resolution
z0 = 1.5; % sphere z offset
r = 1; % sphere radius
x = linspace(-1,1,N);
y = linspace(-1,1,N);
[X,Y] = meshgrid(x,y);
% pyramid
Triangle1 = -abs(X)+1.5 ;
Triangle2 = -abs(Y)+1.5 ;
Pyramid = min(Triangle1, Triangle2);
% half-sphere (hemisphere)
sqrt_term = r^2 - X.^2 - Y.^2;
HalfSphere = -sqrt(sqrt_term) + z0;
HalfSphere(sqrt_term < 0) = inf;
Z = min(HalfSphere, Pyramid);
surf(X,Y,Z)
shading interp
view(70,35)
axis tight

Shade a subset of a sphere's surface in MATLAB

I'm attempting to generate a plot of a hemisphere with a shaded area on the surface bound by max/min values of elevation and azimuth. Essentially I'm trying to reproduce this:
Generating the hemisphere is easy enough, but past that I'm stumped. Any ideas?
Here's the code I used to generate this sphere:
[x,y,z] = sphere;
x = x(11:end,:);
y = y(11:end,:);
z = z(11:end,:);
r = 90;
surf(r.*x,r.*y,r.*z,'FaceColor','yellow','FaceAlpha',0.5);
axis equal;
If you want to highlight a certain area of your hemisphere, first you decide the minimum and maximum azimuth (horizontal sweep) and elevation (vertical sweep) angles. Once you do this, take your x,y,z co-ordinates and convert them into their corresponding angles in spherical co-ordinates. Once you do that, you can then subset your x,y,z co-ordinates based on these angles. To convert from Cartesian to spherical, you would thus do:
Source: Wikipedia
theta is your elevation while phi is your azimuth. r would be the radius of the sphere. Because sphere generates co-ordinates for a unit sphere, r = 1. Therefore, to calculate the angles, we simply need to do:
theta = acosd(z);
phi = atan2d(y, x);
Take note that the elevation / theta is restricted 0 to 180 degrees, while the azimuth / phi is restricted between -180 to 180 degrees. Because you're only creating half of a sphere, the elevation should simply vary from 0 to 90 degrees. Also note that acosd and atan2d return the result in degrees. Now that we're here, you just have to subset what part of the sphere you want to draw. For example, let's say we wanted to restrict the sphere such that the min. and max. azimuth span from -90 to 90 degrees while the elevation only spans from 0 to 45 degrees. As such, let's find those x,y,z co-ordinates that satisfy these constraints, and ensure that anything outside of this range is set to NaN so that these points aren't drawn on the sphere. As such:
%// Change your ranges here
minAzimuth = -90;
maxAzimuth = 90;
minElevation = 0;
maxElevation = 45;
%// Compute angles - assuming that you have already run the code for sphere
%// [x,y,z] = sphere;
%// x = x(11:end,:);
%// y = y(11:end,:);
%// z = z(11:end,:);
theta = acosd(z);
phi = atan2d(y, x);
%%%%%// Begin highlighting logic
ind = (phi >= minAzimuth & phi <= maxAzimuth) & ...
(theta >= minElevation & theta <= maxElevation); % // Find those indices
x2 = x; y2 = y; z2 = z; %// Make a copy of the sphere co-ordinates
x2(~ind) = NaN; y2(~ind) = NaN; z2(~ind) = NaN; %// Set those out of bounds to NaN
%%%%%// Draw our original sphere and then the region we want on top
r = 90;
surf(r.*x,r.*y,r.*z,'FaceColor','white','FaceAlpha',0.5); %// Base sphere
hold on;
surf(r.*x2,r.*y2,r.*z2,'FaceColor','red'); %// Highlighted portion
axis equal;
view(40,40); %// Adjust viewing angle for better view
... and this is what I get:
I've made the code modular so that all you have to do is change the four variables that are defined at the beginning of the code, and the output will highlight that desired part of the hemisphere that are bounded by those min and max ranges.
Hope this helps!
One option is to create an array with the corresponding color you want to attribute to each point.
A minimal example (use trigonometry to convert your azimuth and elevation to logical conditions on x, y, and z):
c=(y>0).*(x>0).*(z>0.1).*(z<0.5);
c(c==0)=NaN;
surf(r.*x,r.*y,r.*z,c ,'FaceAlpha',0.5); axis equal;
yields this:
Note: this only works with the resolution of the grid. (i.e each 'patch' of the surface can have a different color). To exactly reproduce your plot, you might want to superpose the grid sphere with another one that has a much larger number of grid points on which you apply the above code.

quiver not drawing arrows just lots of blue, matlab

Can somebody tell me what I am doing wrong with the quiver plotting function when I don't really get arrows, it just fills the empty space with lots of blue.Look at the image below and then look at my code.
This is just a part of my contour since this eats up proccessing power if I try to draw it larger. But my function, the contours and everything else works, it's just the quiver I'm having trouble with.
interval = -100:100;
[X Y] = meshgrid(interval, interval);
h = figure;
contour(X, Y, Z);
hold on;
[FX,FY] = gradient(-Z);
quiver(X, Y, FX, FY);
hold off;
If I make my matrix more sparse, e.g. with "interval = linspace(-800, 1600, 1200);" the result will look like this:
EDIT:
What I need are contour lines like that, but the arrows should flow with them. Right now these just look like dots, even if I zoom in further. If I zoom out the entire window will be blue.
Here is the script in its entirety if anyone wants to play with it to figure this out.
m1 = 1;
m2 = 0.4;
r1 = [1167 0 0];
r2 = [-467 0 0];
G = 9.82;
w = sqrt( G*(m1+m2) / norm(r1-r2)^3 );
interval = linspace(-800, 1600, 1200);
% Element-wise 2-norm
ewnorm = #(x,y) ( x.^2 + y.^2 ).^(1/2);
% Element-wise cross squared
ewcross2 = #(w,x,y) w^2.*( x.*x + y.*y );
[X Y] = meshgrid(interval, interval);
Z = - G*m1 ./ ewnorm( X-r1(1), Y-r1(2) ) - G*m2 ./ ewnorm( X-r2(1), Y-r2(2) ) - 1/2*ewcross2(w,X,Y);
h = figure;
contour(Z);
daspect([1 1 1]);
saveas(h, 'star1', 'eps');
hold on;
[FX,FY] = gradient(-Z);
quiver(X, Y, FX,FY);
hold off;
The problem is that the mesh is too dense. You only want to have as few elements as necessary to generate a useful mesh. As such, try reducing the density of the mesh:
interval = -100:2:100
If you're going to be changing the limits often, you probably want to avoid using the X:Y:Z formulation. Use the linspace function instead:
interval = linspace(-100,100,10);
This will ensure that no matter what your limits, your mesh will be 10x10. In the comment below, you mention that the arrows are appearing as dots when you use a very large mesh. This is to be expected. The arrows reflect "velocity" at a given point. When your plot is scaled out to a very large degree, then the velocity at any given point on the plot will be almost 0, hence the very small arrows. Check out the quiver plot documentation, as well as the quivergroup properties, to see more details.
If you absolutely must see arrows at a large scale, you can try setting the AutoScale property to off, or increasing the AutoScaleFactor:
quiver(X, Y, FX, FY, 'AutoScale', 'off');
quiver(X, Y, FX, FY, 'AutoScaleFactor', 10);
You may also want to play with the MarkerSize and MaxHeadSize properties. I really just suggest looking at all the QuiverGroup properties and trying things out.
You could use a threshold
interval = -100:100;
[X Y] = meshgrid(interval, interval);
h = figure;
contour(X, Y, Z);
hold on;
[FX,FY] = gradient(-Z);
GM = sqrt(FX.^2 + FY.^2);
threshold = 0.1;
mask = GM > threshold;
quiver(X(mask), Y(mask), FX(mask), FY(mask));
hold off;
This will show only vectors with a magnitude > 0.1;