Related
I made two 3D plots on the same axis. now I desire to give them different colors for easy identification. How do I do this coloring? The MATLAB code is shown below.
tic
Nx = 50;
Ny = 50;
x = linspace(0,1,Nx);
y = linspace(0,0.5,Ny);
[X,Y] = meshgrid(x,y);
[M,N] = size(X);
for m=1:M
for n=1:N
%get x,y coordinate
x_mn = X(m,n);
y_mn = Y(m,n);
%%% X=D2 and Y=D1
%Check if x_mn and y_mn satisfy requirement
if(x_mn >= y_mn)
%evaluate function 1
Z(m,n) = (x_mn^2 - 2*x_mn*y_mn + y_mn^2);
Z_1(m,n) = (x_mn^2);
elseif(x_mn < y_mn)
%evaluate function 2
Z(m,n) = 0;
Z_1(m,n) = (x_mn^2);
%% Z(m,n) = 2*(2*x_mn*y_mn + y_mn - y_mn^2 - 2*x_mn);
else
Z(m,n) = 0;
end
end
end
%Plot the surface
figure
surf(X,Y,Z) %first plot
surfc(X,Y,Z)
hold on
surf(X,Y,Z_1) %second plot
xlabel('Dm');
ylabel('D');
zlabel('pR');
grid on
shading interp
toc
disp('DONE!')
How can I create two differently colored surfaces?
figure
surf(X,Y,Z) %first plot
surfc(X,Y,Z)
hold on
surf(X,Y,Z_1)
Your surfc() call actually overwrites your surf() call, is this intended?
As to your colour: the documentation is a marvellous thing:
surfc(X,Y,Z,C) additionally specifies the surface color.
In other words: just specify the colour as you want it. C needs to be a matrix of size(Z) with the desired colours, i.e. set all of them equal to create an monocoloured surface:
x = 1:100;
y = 1:100;
z = rand(100);
figure;
surfc(x,y,z,ones(size(z)))
hold on
surfc(x,y,z+6,ones(size(z))+4)
Results in (MATLAB R2007b, but the syntax is the same nowadays)
Description of the program is as below:
I take 3 coordinates from a file and I drew a triangle
I want to plot a grid and if the grid points are in a triangle, I want to plot a black circle, otherwise a red circle.
The method I used for checking if the point is inside a triangle is, if the point (xco,yco) is inside the triangle, the sum of areas of small triangles it makes with three other points is equal to the area of the triangle.
So my if statement is if the total area = area of triangle -> plot black circle, otherwise red circle.
The problem is, even though some points made the Total area to be equal to the area of the triangle plot black circle isn't plotted and red circle is plotted instead.
It does seem random and I can't figure out this simple problem.
So could you help me with the plotting the the points?
figure()
% Loading the data from .mat file
A = load('triangle_a.mat','pt1');
B = load('triangle_a.mat','pt2');
C = load('triangle_a.mat','pt3');
% Assigning values of array from .mat into each variable
x1 = A.pt1(1,1);
y1 = A.pt1(1,2);
x2 = B.pt2(1,1);
y2 = B.pt2(1,2);
x3 = C.pt3(1,1);
y3 = C.pt3(1,2);
% Drawing coordinates of a triangle on a grid
plot(x1, y1,'or');
hold on
plot(x2, y2,'or');
hold on
plot(x3, y3,'or');
hold on
% Joining three coordinates to make a triangle
plot ([x1,x2],[y1,y2],'-b');
plot ([x1,x3],[y1,y3],'-b');
plot ([x3,x2],[y3,y2],'-b');
xmin = A_coor(1,1);
xmax = B_coor(1,1);
ymin = A_coor(1,2);
ymax = C_coor(1,2);
xgrid = xmin-1:0.5:xmax+1;
ygrid = ymin-1:0.5:ymax+1;
tri_x = [x1 x2 x3];
tri_y = [y1 y2 y3];
area = polyarea(tri_x,tri_y);
% Making a grid
for x = 1:1:numel(xgrid)
for y = 1:1:numel(ygrid)
xco = xgrid(1,x);
yco = ygrid(1,y);
aa = [xco, x2, x3];
bb = [yco, y2, y3];
cc = [x1, xco, x3];
dd = [y1, yco, y3];
ee = [x1,x2,xco];
ff = [y1,y2,yco];
area1 = polyarea(aa,bb);
area2 = polyarea(cc,dd);
area3 = polyarea(ee,ff);
totarea = area1 + area2 + area3;
if totarea == area
plot(xco,yco,'ok');
else
plot(xco,yco,'.r');
end
end
end
My code worked after I changed the condition of if statement for making a grid section. (Thanks to Hoki for suggestion)
Before
if totarea == area
After
if abs(area-totarea)<0.002;)
You can determine whether a point is inside an arbitrary polygon by using the MATLAB function inpolygon.
How to generate a 3D plot of a parametric curve with the orthographic projections on the inside walls of the 3D plot, as shown in this video?
I can generate a 3D plot of the curve using the plot3 function but I am lost how to create the blue orthographic projections on the inner walls of the cube ...and the red dashed lines.
P.S.
Also, how to generate the 3 separate "Coordinate Functions" plots (not shown on the diagram above but shown in the video) ...and how to synchronize them together during the animation?
Well, this took a lot of time to write.
clear;clc;close all
t = 0:0.01:6;
x = cos(5*t);
y = sin(5*t);
z = t;
%for x,y,z as as general function of t
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
zmin = min(z);
zmax = max(z);
orangeColorRGB = [0.8500 0.3250 0.0980];
%3D plot
plot3DSubplot = subplot(3,2,[1 3 5]);
view(3)
grid on
title('Parametric curve in R^3')
xlabel('x(t)')
ylabel('y(t)')
zlabel('z(t)')
xyProjectionOffset = -0.5;
xzProjectionOffset = 1.5;
yzProjectionOffset = 1.5;
xlim([xmin max(xmax, yzProjectionOffset)])
ylim([ymin max(ymax, xzProjectionOffset)])
zlim([min(zmin ,xyProjectionOffset) zmax])
curve3D_marker = animatedline(plot3DSubplot,x(1),y(1),z(1),'Marker','o','Color','magenta'); %marker in 3D
curve3D = animatedline(plot3DSubplot, x(1),y(1),z(1),'Color','magenta','LineStyle','-','LineWidth',2); %3D curve
curve3D_projectedToXY = animatedline(plot3DSubplot,x(1),y(1),xyProjectionOffset,'Color','blue','LineStyle','-','LineWidth',2); %projection on xy
curve3D_projectionStraightLineToXY = animatedline(plot3DSubplot,x(1),y(1),z(1),'Color',orangeColorRGB,'LineStyle','--','LineWidth',2); %projection on xy
curve3D_projectedToXZ = animatedline(plot3DSubplot,x(1),xzProjectionOffset,z(1),'Color','blue','LineStyle','-','LineWidth',2); %projection on xz
curve3D_projectionStraightLineToXZ = animatedline(plot3DSubplot,x(1),y(1),z(1),'Color',orangeColorRGB,'LineStyle','--','LineWidth',2); %projection on xy
curve3D_projectedToYZ = animatedline(plot3DSubplot,yzProjectionOffset,y(1),z(1),'Color','blue','LineStyle','-','LineWidth',2); %projection on yz
curve3D_projectionStraightLineToYZ = animatedline(plot3DSubplot,x(1),y(1),z(1),'Color',orangeColorRGB,'LineStyle','--','LineWidth',2); %projection on xy
%x plot
xPlot = subplot(3,2,2);
grid on
title('Coordinates')
ylabel('cos(5t)')
xlim([t(1) t(end)])
ylim([xmin xmax])
xCoordinate = animatedline(xPlot,t(1),x(1),'Color','blue');
xCoordinate_projectedValue = animatedline(xPlot,t(1),x(1),'Color',orangeColorRGB,'LineStyle','--');
xCoordinateMarker = animatedline(xPlot,t(1),x(1),'Color','blue','Marker','o');
%y plot
yPlot = subplot(3,2,4);
grid on
ylabel('sin(5t)')
xlim([t(1) t(end)])
ylim([ymin ymax])
yCoordinate = animatedline(yPlot,t(1),y(1),'Color','blue');
yCoordinate_projectedValue = animatedline(yPlot,t(1),y(1),'Color',orangeColorRGB,'LineStyle','--');
yCoordinateMarker = animatedline(yPlot,t(1),y(1),'Color','blue','Marker','o');
%z plot
zPlot = subplot(3,2,6);
grid on
ylabel('t')
xlim([t(1) t(end)])
ylim([zmin zmax])
zCoordinate = animatedline(zPlot,t(1),z(1),'Color','blue');
zCoordinate_projectedValue = animatedline(zPlot,t(1),z(1),'Color',orangeColorRGB,'LineStyle','--');
zCoordinateMarker = animatedline(zPlot,t(1),z(1),'Color','blue','Marker','o');
for i=2:length(t)
% 3D plot & projections
addpoints(curve3D,x(i),y(i),z(i))
clearpoints(curve3D_marker)
addpoints(curve3D_marker,x(i),y(i),z(i))
%XY projection
addpoints(curve3D_projectedToXY,x(i),y(i),xyProjectionOffset)
clearpoints(curve3D_projectionStraightLineToXY)
addpoints(curve3D_projectionStraightLineToXY,[x(i) x(i)],[y(i) y(i)],[xyProjectionOffset z(i)])
%XZ projection
addpoints(curve3D_projectedToXZ,x(i),xzProjectionOffset,z(i))
clearpoints(curve3D_projectionStraightLineToXZ)
addpoints(curve3D_projectionStraightLineToXZ,[x(i) x(i)],[xzProjectionOffset y(i)],[z(i) z(i)])
%YZ projection
addpoints(curve3D_projectedToYZ,1.5,y(i),z(i))
clearpoints(curve3D_projectionStraightLineToYZ)
addpoints(curve3D_projectionStraightLineToYZ,[yzProjectionOffset x(i)],[y(i) y(i)],[z(i) z(i)])
%2D x plot
addpoints(xCoordinate,t(i),x(i))
clearpoints(xCoordinate_projectedValue)
addpoints(xCoordinate_projectedValue,[t(1) t(i)],[x(i) x(i)])
clearpoints(xCoordinateMarker)
addpoints(xCoordinateMarker,t(i),x(i))
%2D y plot
addpoints(yCoordinate,t(i),y(i))
clearpoints(yCoordinate_projectedValue)
addpoints(yCoordinate_projectedValue,[t(1) t(i)],[y(i) y(i)])
clearpoints(yCoordinateMarker)
addpoints(yCoordinateMarker,t(i),y(i))
%2D z plot
addpoints(zCoordinate,t(i),z(i))
clearpoints(zCoordinate_projectedValue)
addpoints(zCoordinate_projectedValue,[t(1) t(i)],[z(i) z(i)])
clearpoints(zCoordinateMarker)
addpoints(zCoordinateMarker,t(i),z(i))
drawnow
end
Outside the for-loop:
Define your subplots.
Define your lines in a somewhat object-oriented approach. Define lines with animatedline
including their
properties
(color, linewidth etc).
Define lines with animatedline with the intention to use only the marker.
Inside the for-loop:
Add the new points to those lines using addpoints.
Regarding the projections to the xy,yz,xz planes:
The projection of a point (x0,y0,z0) to the xy plane defined by z = -2 is (x0,y0,-2). Therefore when you have a point (x,y,z) you project to the correct plane in the same way.
For the vertical lines that connect the current point to the projection, at every update to the plot remove previous points and redraw them. That's why I first call
clearpoints
to remove any previous points and then addpoints to add 2 points for a straight line from the projection to the actual (x,y,z) point.
For the "marker-lines", again clearpoints and then add the new point.
After adding the points to all the lines, call
drawnow
before the next loop iteration for all lines to be updated at the same time (and for the updates to appear synchronized).
I have about four series of data on a Matlab plot, two of them are quite close and can only be differentiated with a zoom. How do I depict the zoomed part within the existing plot for the viewer. I have checked similar posts but the answers seem very unclear.
I look for something like this:
Here is a suggestion how to do this with MATLAB. It may need some fine tuning, but it will give you the result:
function pan = zoomin(ax,areaToMagnify,panPosition)
% AX is a handle to the axes to magnify
% AREATOMAGNIFY is the area to magnify, given by a 4-element vector that defines the
% lower-left and upper-right corners of a rectangle [x1 y1 x2 y2]
% PANPOSTION is the position of the magnifying pan in the figure, defined by
% the normalized units of the figure [x y w h]
%
fig = ax.Parent;
pan = copyobj(ax,fig);
pan.Position = panPosition;
pan.XLim = areaToMagnify([1 3]);
pan.YLim = areaToMagnify([2 4]);
pan.XTick = [];
pan.YTick = [];
rectangle(ax,'Position',...
[areaToMagnify(1:2) areaToMagnify(3:4)-areaToMagnify(1:2)])
xy = ax2annot(ax,areaToMagnify([1 4;3 2]));
annotation(fig,'line',[xy(1,1) panPosition(1)],...
[xy(1,2) panPosition(2)+panPosition(4)],'Color','k')
annotation(fig,'line',[xy(2,1) panPosition(1)+panPosition(3)],...
[xy(2,2) panPosition(2)],'Color','k')
end
function anxy = ax2annot(ax,xy)
% This function converts the axis unites to the figure normalized unites
% AX is a handle to the figure
% XY is a n-by-2 matrix, where the first column is the x values and the
% second is the y values
% ANXY is a matrix in the same size of XY, but with all the values
% converted to normalized units
pos = ax.Position;
% white area * ((value - axis min) / axis length) + gray area
normx = pos(3)*((xy(:,1)-ax.XLim(1))./range(ax.XLim))+ pos(1);
normy = pos(4)*((xy(:,2)-ax.YLim(1))./range(ax.YLim))+ pos(2);
anxy = [normx normy];
end
Note that the units of areaToMagnify are like the axis units, while the units of panPosition are between 0 to 1, like the position property in MATLAB.
Here is an example:
x = -5:0.1:5;
subplot(3,3,[4 5 7 8])
plot(x,cos(x-2),x,sin(x),x,-x-0.5,x,0.1.*x+0.1)
ax = gca;
area = [-0.4 -0.4 0.25 0.25];
inlarge = subplot(3,3,3);
panpos = inlarge.Position;
delete(inlarge);
inlarge = zoomin(ax,area,panpos);
title(inlarge,'Zoom in')
I'm doing Gaussian processes and I calculated a regression per year from a given matrix where each row represents a year , so the code is:
M1 = MainMatrix; %This is the given Matrix
ker =#(x,y) exp(-1013*(x-y)'*(x-y));
[ns, ms] = size(M1);
for N = 1:ns
x = M1(N,:);
C = zeros(ms,ms);
for i = 1:ms
for j = 1:ms
C(i,j)= ker(x(i),x(j));
end
end
u = randn(ms,1);
[A,S, B] = svd(C);
z = A*sqrt(S)*u; % z = A S^.5 u
And I wanna plotting each regression in a Graph 3D as the below:
I know that plot is a ribbon, but I have not idea how can I do that
The desired plot can be generated without the use of ribbon. Just use a surf-plot for all the prices and a fill3-plot for the plane at z=0. The boundaries of the plane are calculated from the actual limits of the figure. Therefore we need to set the limits before plotting the plane. Then just some adjustments are needed to generate almost the same appearance.
Here is the code:
% generate some data
days = (1:100)';
price = days*[0.18,-0.08,0.07,-0.10,0.12,-0.08,0.05];
price = price + 0.5*randn(size(price));
years = 2002+(1:size(price,2));
% prepare plot
width = 0.6;
X = ones(size(price,1),1)*0.5;
X = [-X,X]*width;
figure; hold on;
% plot all 'ribbons'
for i = 1:size(price,2)
h = surf([days,days],X+years(i),[price(:,i),price(:,i)]);
set(h,'MeshStyle','column');
end
% set axis limits
set(gca,'ZLim',[-20,20]);
% plot plane at z=0
limx = get(gca,'XLim');
limy = get(gca,'YLim');
fill3(reshape([limx;limx],1,[]),[flip(limy),limy],zeros(1,4),'g','FaceAlpha',0.2)
% set labels
xlabel('Day of trading')
ylabel('Year')
zlabel('Normalized Price')
% tweak appearance
set(gca,'YTick',years);
set(gca,'YDir','reverse');
view([-38,50])
colormap jet;
grid on;
%box on;
This is the result:
That's a ribbon plot with an additional surface at y=0 which can be drawn with fill3