Related
I have a plot in Matlab as following, I want to add some parameters to the figure like the figure which I have added. Could you help me with how to solve that? Thank you so much.
delta = 0.5;
I1=2;
I2 =4;
T = 5;
tau = 0.5;
b = 8;
a = 6;
c = 8;
d = 4;
t = [0:0.001:5];
y =(a-b*exp(-tau*t)).*(t>=0 & t<delta*T )+(-d+c*exp(-tau*(t-delta*T))).*(t>=delta*T & t<=T);
plot(t,y , 'b', 'LineWidth',1.8)
hold on
x = [0:0.01:12];
max = 4*ones(1,1201);
min = -2*ones(1,1201);
z = 0*ones(1,1201);
plot(x,max , '--g', 'LineWidth',1)
hold on
plot(x,min , '--g', 'LineWidth',1)
plot(2,min , '--g', 'LineWidth',1)
plot(x,z , 'k', 'LineWidth',1.7)
axis([0 6 -4 6])
I think this code might generate something close for what you are looking. It is important to say that the arrows for x and y can be added using the same "annotation command".
delta = 0.5;
I1=2;
I2 =4;
T = 5;
tau = 0.5;
b = 8;
a = 6;
c = 8;
d = 4;
t = [0:0.001:5];
y =(a-b*exp(-tau*t)).*(t>=0 & t<delta*T )+(-d+c*exp(-tau*(t-delta*T))).*(t>=delta*T & t<=T);
plot(t,y , 'b', 'LineWidth',1.8,'DisplayName',"Data")
% Change the y limits
ylim([-4 6])
hold on
% %% Set the horizontal lines and its name in the y axis
% MAX LINE - Create a yline Cte along the plot
hLine = yline(4);
hLine.LineWidth = 1;
hLine.Color = "g";
hLine.LineStyle = "--";
hLine.DisplayName = "Max Line";
% MIN LINE - Create a yline Cte along the plot
hLine = yline(-2);
hLine.LineWidth = 1;
hLine.Color = "g";
hLine.LineStyle = "--";
hLine.DisplayName = "Min Line";
% Zero LINE - Create a yline Cte along the plot
hLine = yline(0);
hLine.LineWidth = 1.7;
hLine.Color = "k";
hLine.LineStyle = "-";
% Change the "name" in the y axis
hAxis = gca;
% Get index
% - when y is equal to "Max" in this case 4
% - when y is equal to "MIN" in this case -2
idx = hAxis.YTick == 4;
hAxis.YTickLabel{idx} = 'X';
idx = hAxis.YTick == -2;
hAxis.YTickLabel{idx} = 'Y';
% %% Set the vertical lines and its name in the x axis
% Delta LINE - Create a xline Cte along the plot
hLine = xline(2.5);
hLine.LineWidth = 1;
hLine.Color = "k";
hLine.LineStyle = "-";
% MIN LINE - Create a yline Cte along the plot
hLine = xline(4);
hLine.LineWidth = 1;
hLine.Color = "k";
hLine.LineStyle = "-";
% Add the notes
annotation('textbox',[.55 .2 .3 .3],"String","Delta",...
'FitBoxToText','on','LineStyle','none')
annotation('textbox',[0.8 0.2 .3 .3],"String","A",...
'FitBoxToText','on','LineStyle','none')
The previous code will generate the next figure.
I'm trying to make a compound plot in matlab, with a data table below. Just like the one in this image (yes, that one was made in excel):
As far as I go, I'm able to make the plot, but have no idea of how to make the table below. Here's my code:
y = [1,4; 0,0; 0,0; 1,0; 4,5; 21,10; 13,9; 3,3; 2,NaN; 0,NaN; 0,NaN; 1,NaN];
z = [16,34; 16,17; 26,17; 27,21; 42,37; 60,45; 45,47; 37,33; 28,NaN; 14,NaN;
16,NaN; 21,NaN];
z(z==0) = nan;
aa=max(y);
P= max(aa);
bb=max(z);
q= max(bb);
yyaxis left
a=bar(y,1,'EdgeColor','none');
ylabel('Días');
ylim([0 (P+2)]);
yyaxis right
b=plot(z);
ylim([0 (q+5)]);
ylabel('µg/m³');
b(1).LineWidth = 2;
b(1).Marker = 's';
b(1).MarkerFaceColor = [1 0.5216 0.2];
b(2).Marker = 'o';
b(2).MarkerFaceColor = [0 0.5255 0.9020];
b(2).LineWidth = 2;
b(2).Color = [0 0.4392 0.7529];
XTickLabel={'Enero' ; 'Febrero' ; 'Marzo'; 'Abril' ; 'Mayo' ; 'Junio' ;
'Julio' ; 'Agosto' ; 'Septiembre' ; 'Octubre' ; 'Noviembre' ;
'Diciembre'};
XTick=[1:12];
set(gca, 'XTick',XTick);
set(gca, 'XTickLabel', XTickLabel);
set(gca, 'XTickLabelRotation', 45);
set(gcf, 'Position', [100, 100, 1000, 350])
%Maximizar el espacio de la figura
ax = gca;
outerpos = ax.OuterPosition;
ti = ax.TightInset;
left = outerpos(1) + ti(1);
bottom = outerpos(2) + ti(2);
ax_width = outerpos(3) - ti(1) - ti(3);
ax_height = outerpos(4) - ti(2) - ti(4);
ax.Position = [left bottom ax_width ax_height];
%%%%%% Grilla %%%%%%%
grid on
legend('Total Episodios 2017','Total Episodios 2018','Conc.Prom. Mensual
2017','Conc.Prom. Mensual 2018');
%%% Colores %%%%
barmap=[1 0.4 0; 0 0.4392 0.7529];
colormap(barmap);
I would deeply appreciate any help you could give me.
figure;
% Plot first part
subplot(2,1,1);
x = [2 3 4 1 2 4 12 45];
plot(x)
% Plot table
ha = subplot(2,1,2);
pos = get(ha,'Position');
un = get(ha,'Units');
ht = uitable('Units',un,'Data',randi(100,10,3), 'Position',pos);
I want to move a red star marker along the spiral trajectory with an equal distance of 5 units between the red star points on its circumference like in the below image.
vertspacing = 10;
horzspacing = 10;
thetamax = 10*pi;
% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/2/pi;
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta)+50;
y = b*theta.*sin(theta)+50;
% Calculation of equidistant (xi,yi) points on spiral.
smax = 0.5*b*thetamax.*thetamax;
s = 0:horzspacing:smax;
thetai = sqrt(2*s/b);
xi = b*thetai.*cos(thetai);
yi = b*thetai.*sin(thetai);
plot(x,y,'b-');
hold on
I want to get a figure that looks like the following:
This is my code for the circle trajectory:
% Initialization steps.
format long g;
format compact;
fontSize = 20;
r1 = 50;
r2 = 35;
r3= 20;
xc = 50;
yc = 50;
% Since arclength = radius * (angle in radians),
% (angle in radians) = arclength / radius = 5 / radius.
deltaAngle1 = 5 / r1;
deltaAngle2 = 5 / r2;
deltaAngle3 = 5 / r3;
theta1 = 0 : deltaAngle1 : (2 * pi);
theta2 = 0 : deltaAngle2 : (2 * pi);
theta3 = 0 : deltaAngle3 : (2 * pi);
x1 = r1*cos(theta1) + xc;
y1 = r1*sin(theta1) + yc;
x2 = r2*cos(theta2) + xc;
y2 = r2*sin(theta2) + yc;
x3 = r3*cos(theta3) + xc;
y3 = r3*sin(theta3) + yc;
plot(x1,y1,'color',[1 0.5 0])
hold on
plot(x2,y2,'color',[1 0.5 0])
hold on
plot(x3,y3,'color',[1 0.5 0])
hold on
% Connecting Line:
plot([70 100], [50 50],'color',[1 0.5 0])
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
drawnow;
axis square;
for i = 1 : length(theta1)
plot(x1(i),y1(i),'r*')
pause(0.1)
end
for i = 1 : length(theta2)
plot(x2(i),y2(i),'r*')
pause(0.1)
end
for i = 1 : length(theta3)
plot(x3(i),y3(i),'r*')
pause(0.1)
end
I can't think of a way to compute distance along a spiral, so I'm approximating it with circles, in hopes that it will still be useful.
My solution relies on the InterX function from FEX, to find the intersection of circles with the spiral. I am providing an animation so it is easier to understand.
The code (tested on R2017a):
function [x,y,xi,yi] = q44916610(doPlot)
%% Input handling:
if nargin < 1 || isempty(doPlot)
doPlot = false;
end
%% Initialization:
origin = [50,50];
vertspacing = 10;
thetamax = 5*(2*pi);
%% Calculation of (x,y) - underlying archimedean spiral.
b = vertspacing/(2*pi);
theta = 0:0.01:thetamax;
x = b*theta.*cos(theta) + origin(1);
y = b*theta.*sin(theta) + origin(2);
%% Calculation of equidistant (xi,yi) points on spiral.
DST = 5; cRes = 360;
numPts = ceil(vertspacing*thetamax); % Preallocation
[xi,yi] = deal(NaN(numPts,1));
if doPlot && isHG2() % Plots are only enabled if the MATLAB version is new enough.
figure(); plot(x,y,'b-'); hold on; axis equal; grid on; grid minor;
hAx = gca; hAx.XLim = [-5 105]; hAx.YLim = [-5 105];
hP = plot(xi,yi,'r*');
else
hP = struct('XData',xi,'YData',yi);
end
hP.XData(1) = origin(1); hP.YData(1) = origin(2);
for ind = 2:numPts
P = InterX([x;y], makeCircle([hP.XData(ind-1),hP.YData(ind-1)],DST/2,cRes));
[~,I] = max(abs(P(1,:)-origin(1)+1i*(P(2,:)-origin(2))));
if doPlot, pause(0.1); end
hP.XData(ind) = P(1,I); hP.YData(ind) = P(2,I);
if doPlot, pause(0.1); delete(hAx.Children(1)); end
end
xi = hP.XData(~isnan(hP.XData)); yi = hP.YData(~isnan(hP.YData));
%% Nested function(s):
function [XY] = makeCircle(cnt, R, nPts)
P = (cnt(1)+1i*cnt(2))+R*exp(linspace(0,1,nPts)*pi*2i);
if doPlot, plot(P,'Color',lines(1)); end
XY = [real(P); imag(P)];
end
end
%% Local function(s):
function tf = isHG2()
try
tf = ~verLessThan('MATLAB', '8.4');
catch
tf = false;
end
end
function P = InterX(L1,varargin)
% DOCUMENTATION REMOVED. For a full version go to:
% https://www.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections
narginchk(1,2);
if nargin == 1
L2 = L1; hF = #lt; %...Avoid the inclusion of common points
else
L2 = varargin{1}; hF = #le;
end
%...Preliminary stuff
x1 = L1(1,:)'; x2 = L2(1,:);
y1 = L1(2,:)'; y2 = L2(2,:);
dx1 = diff(x1); dy1 = diff(y1);
dx2 = diff(x2); dy2 = diff(y2);
%...Determine 'signed distances'
S1 = dx1.*y1(1:end-1) - dy1.*x1(1:end-1);
S2 = dx2.*y2(1:end-1) - dy2.*x2(1:end-1);
C1 = feval(hF,D(bsxfun(#times,dx1,y2)-bsxfun(#times,dy1,x2),S1),0);
C2 = feval(hF,D((bsxfun(#times,y1,dx2)-bsxfun(#times,x1,dy2))',S2'),0)';
%...Obtain the segments where an intersection is expected
[i,j] = find(C1 & C2);
if isempty(i), P = zeros(2,0); return; end
%...Transpose and prepare for output
i=i'; dx2=dx2'; dy2=dy2'; S2 = S2';
L = dy2(j).*dx1(i) - dy1(i).*dx2(j);
i = i(L~=0); j=j(L~=0); L=L(L~=0); %...Avoid divisions by 0
%...Solve system of eqs to get the common points
P = unique([dx2(j).*S1(i) - dx1(i).*S2(j), ...
dy2(j).*S1(i) - dy1(i).*S2(j)]./[L L],'rows')';
function u = D(x,y)
u = bsxfun(#minus,x(:,1:end-1),y).*bsxfun(#minus,x(:,2:end),y);
end
end
Result:
Note that in the animation above, the diameter of the circle (and hence the distance between the red points) is 10 and not 5.
The below code is something that I am cooking up. I am plotting the orbits of the Sun, Mercury, Earth and the Moon. I have gotten this far into the project but the orbit of Mercury is terrifyingly wrong. This is seen by typing "SunEarthMoon(2,50)" at the command prompt and viewing the bottom left plot. The logic behind the project is utilizing Newton's Second Law toggled with the command "ode45" to find the positions of the bodies during a given time interval. I've been staring at this for far too long. Can anyone help to fix the orbit of Mercury?
function [] = SunEarthMoon(years,framerate)
%% Clean Up
close all
clc
%% Initializaion
x_earth = 147300000000; % [m]
x_mercury = 57.91e9; % [m]
v_earth = 30257; % [m/s]
v_mercury = 47362; % [m/s]
r_sat = 384748000; % earth surface [m]
r_earth = 6367000; % earth radius [m]
v_sat = 1023; % relative velocity from earth [m/s]
a = 5.145; % Angle to vertical (y) axis
b = 90; % Angle to horizontal (x) axis in xz plane
x_earth_o = [x_earth; 0; 0];
x_sun_o = [0; 0; 0];
x_mercury_o = [x_mercury; 0; 0];
x_sat_o = [x_earth+r_sat+r_earth; 0; 0];
v_earth_o = [0; v_earth; 0];
v_sun_o = [0; 0; 0];
v_mercury_o = [0; v_mercury; 0];
v_sat_o = v_sat*[cos(pi/180*b)*sin(pi/180*a); cos(pi/180*a); sin(pi/180*b)*sin(pi/180*a)] + v_earth_o;
interval = years*[0 31536000];
%% Error Control
h = [0.01 36000];
tol = 100000;
Options.AbsTol = tol;
Options.MaxStep = h(2);
Options.InitialStep = h(1);
%% Analysis
ao = [x_earth_o; v_earth_o; x_sun_o; v_sun_o; x_sat_o; v_sat_o; x_mercury_o; v_mercury_o];
[t, x] = ode45(#earthfinal,interval,ao,Options);
for i = 1:length(t)
R1(i) = (x(i,13)-x(i,1));
R2(i) = (x(i,14)-x(i,2));
R3(i) = (x(i,15)-x(i,3));
R(i) = sqrt(R1(i)^2+R2(i)^2+R3(i)^2);
end
T_index_earth = find([1; x(:,4)].*[x(:,4);1]<=0);
T_index_moon = find([1; R2(:)].*[R2(:); 1]<=0);
for i = 4:length(T_index_earth)
T_earth_semi(i-3) = (t(T_index_earth(i)-1)-t(T_index_earth(i-2)-1))/24/60/60;
end
T_earth = mean(T_earth_semi);
for i = 4:length(T_index_moon)
T_moon_semi(i-3) = (t(T_index_moon(i)-1)-t(T_index_moon(i-2)-1))/24/60/60;
end
T_moon = mean(T_moon_semi);
D_earth = 0;
for i = 2:(T_index_earth(4)-1)
D_earth = D_earth + sqrt((x(i,1)-x(i-1,1))^2+(x(i,2)-x(i-1,2))^2+(x(i,3)-x(i-1,3))^2);
end
D_moon = 0;
for i = 2:(T_index_moon(4)-1)
D_moon = D_moon + sqrt((R1(i)-R1(i-1))^2+(R2(i)-R2(i-1))^2+(R3(i)-R3(i-1))^2);
end
%% Plots
q = framerate;
scrsz = get(0,'ScreenSize');
figure('position', [0.05*scrsz(3) 0.05*scrsz(4) 0.75*scrsz(3) 0.85*scrsz(4)])
set(gcf,'name','Sun, Earth, and Moon Orbits')
for i = 1:length(t)/q
subplot(2,2,1)
plot3(x(1:i*q,1),x(1:i*q,2),x(1:i*q,3),'g',x(1:i*q,7),x(1:i*q,8),x(1:i*q,9),'r',x(1:i*q,13),x(1:i*q,14),x(1:i*q,15),'b',x(1:i*q,19),x(1:i*q,20),x(1:i*q,21),'black')
axis(1.1*[min(x(:,1)) max(x(:,1)) min(x(:,2)) max(x(:,2)) 2*min(x(:,15)) 2*max(x(:,15))])
xlabel('Universal X Coordinate (m)')
ylabel('Universal Y Coordinate (m)')
zlabel('Universal Z Coordinate (m)')
title('Relative Orbits')
legend('Earth','Sun','Moon')
hold on
plot3(x(i*q,1),x(i*q,2),x(i*q,3),'g-o',x(i*q,7),x(i*q,8),x(i*q,9),'r-o',x(i*q,13),x(i*q,14),x(i*q,15),'b-o',x(i*q,19),x(i*q,20),x(i*q,21),'black-o')
hold off
subplot(2,2,2)
plot3(R1(1:i*q),R2(1:i*q),R3(1:i*q),'b',zeros(1,i*q),zeros(1,i*q),zeros(1,i*q),'g')
axis(1.5*[min(R1) max(R1) min(R2) max(R2) min(R3) max(R3)])
xlabel('Universal X Coordinate (m)')
ylabel('Universal Y Coordinate (m)')
zlabel('Universal Z Coordinate (m)')
title('Relative Moon Orbit About Earth')
hold on
plot3(R1(i*q),R2(i*q),R3(i*q),'b-o',0,0,0,'g-o')
text(0,1.45*max(R2),1.40*max(R3),sprintf('Orbital Period, T = %3.5g days',T_moon))
text(0,1.45*max(R2),1.15*max(R3),sprintf('Orbital Circumference, D = %3.5g gigameters',D_moon*1e-9))
hold off
subplot(2,2,3)
plot(x(1:i*q,1),x(1:i*q,2),'g',x(1:i*q,7),x(1:i*q,8),'r', x(1:i*q,19),x(1:i*q,20),'black')
axis(1.5*[min(x(:,1)) max(x(:,1)) min(x(:,2)) max(x(:,2))])
xlabel('Universal X Coordinate (m)')
ylabel('Universal Y Coordinate (m)')
title('Relative Earth Orbit About Sun')
hold on
plot(x(i*q,1),x(i*q,2),'g-o',x(i*q,7),x(i*q,8),'r-o',x(i*q,19),x(i*q,20),'black-o')
text(1.45*min(x(:,1)),1.40*max(x(:,2)),sprintf('Orbital Period, T = %3.5g days',T_earth))
text(1.45*min(x(:,1)),1.25*max(x(:,2)),sprintf('Orbital Circumference, D = %3.5g gigameters',D_earth*1e-9))
text(1.45*min(x(:,1)),1.40*min(x(:,2)),sprintf('Time, t = %3.3g days',round(t(q*i)/24/60/60)))
hold off
subplot(2,2,4)
plot(t(1:i*q)/(60*60*24),R(1:i*q)/1000,'b')
axis([t(1)/24/60/60 t(end)/24/60/60 0.999*min(R)/1000 1.001*max(R)/1000])
xlabel('Time,t (days)')
ylabel('Orbit Radius, R (km)')
title('Moon-Earth Distance')
hold on
plot(t(i*q)/(60*60*24),R(i*q)/1000,'b-o')
hold off
drawnow
end
end
%% Differential Equation Function
function [udot]= earthfinal(t,u)
m_earth = 5.9742e24; % [kg]
m_mercury = 3.285e23; % [kg]
m_sun = 1.98892e30; % [kg]
m_sat = 11110; % [kg]
G = 6.67300e-11; %[(m)^3(kg)^-1(s)^-2];
d_earth_sun = sqrt((u( 7,1)-u(1,1))^2+(u( 8,1)-u(2,1))^2+(u( 9,1)-u(3,1))^2);
d_earth_sat = sqrt((u(13,1)-u(1,1))^2+(u(14,1)-u(2,1))^2+(u(15,1)-u(3,1))^2);
d_sun_sat = sqrt((u(13,1)-u(7,1))^2+(u(14,1)-u(8,1))^2+(u(15,1)-u(9,1))^2);
d_mercury_sun = sqrt((u(7,1) -u(19,1))^2 + (u(8,1) - u(20,1))^2 + (u(9,1)-u(21,1))^2);
d_mercury_earth = sqrt((u(1,1) -u(19,1))^2 + (u(2,1) - u(20,1))^2 + (u(3,1)-u(21,1))^2);
d_mercury_sat = sqrt((u(13,1) -u(19,1))^2 + (u(14,1) - u(20,1))^2 + (u(15,1)-u(21,1))^2);
% Earth motion
udot( 1,1) = u(4,1);
udot( 2,1) = u(5,1);
udot( 3,1) = u(6,1);
udot( 4,1) = m_sun*G*(u(7,1)-u(1,1))/d_earth_sun^3 + m_sat*G*(u(13,1)-u(1,1))/d_earth_sat^3 + m_mercury*G*(u(19,1)-u(1,1))/d_mercury_earth^3;
udot( 5,1) = m_sun*G*(u(8,1)-u(2,1))/d_earth_sun^3 + m_sat*G*(u(14,1)-u(2,1))/d_earth_sat^3 + m_mercury*G*(u(20,1)-u(2,1))/d_mercury_earth^3;
udot( 6,1) = m_sun*G*(u(9,1)-u(3,1))/d_earth_sun^3 + m_sat*G*(u(15,1)-u(3,1))/d_earth_sat^3 + m_mercury*G*(u(21,1)-u(3,1))/d_mercury_earth^3;
% Sun Motion
udot( 7,1) = u(10,1);
udot( 8,1) = u(11,1);
udot( 9,1) = u(12,1);
udot(10,1) = m_earth*G*(u(1,1)-u(7,1))/d_earth_sun^3 + m_sat*G*(u(13,1)-u(7,1))/d_sun_sat^3 + m_mercury*G*(u(19,1)-u(7,1))/d_mercury_sun^3;
udot(11,1) = m_earth*G*(u(2,1)-u(8,1))/d_earth_sun^3 + m_sat*G*(u(14,1)-u(8,1))/d_sun_sat^3 + m_mercury*G*(u(20,1)-u(8,1))/d_mercury_sun^3;
udot(12,1) = m_earth*G*(u(3,1)-u(9,1))/d_earth_sun^3 + m_sat*G*(u(15,1)-u(9,1))/d_sun_sat^3 + m_mercury*G*(u(21,1)-u(9,1))/d_mercury_sun^3;
% Satellite Motion
udot(13,1) = u(16,1);
udot(14,1) = u(17,1);
udot(15,1) = u(18,1);
udot(16,1) = m_earth*G*(u(1,1)-u(13,1))/d_earth_sat^3 + m_sun*G*(u(7,1)-u(13,1))/d_sun_sat^3 + m_mercury*G*(u(19,1)-u(13,1))/d_mercury_sat^3;
udot(17,1) = m_earth*G*(u(2,1)-u(14,1))/d_earth_sat^3 + m_sun*G*(u(8,1)-u(14,1))/d_sun_sat^3 + m_mercury*G*(u(20,1)-u(14,1))/d_mercury_sat^3;
udot(18,1) = m_earth*G*(u(3,1)-u(15,1))/d_earth_sat^3 + m_sun*G*(u(9,1)-u(15,1))/d_sun_sat^3 + m_mercury*G*(u(21,1)-u(15,1))/d_mercury_sat^3;
% Mercury Motion
udot(19,1) = u(22,1);
udot(20,1) = u(23,1);
udot(21,1) = u(24,1);
udot(22,1) = m_sun*G*(u(7,1)-u(19,1))/d_mercury_sun^3 + m_earth*G*(u(1,1)-u(19,1))/d_mercury_earth^3 + m_sat*G*(u(13,1)-u(19,1))/d_mercury_sat^3;
udot(23,1) = m_sun*G*(u(8,1)-u(20,1))/d_mercury_sun^3 + m_earth*G*(u(2,1)-u(20,1))/d_mercury_earth^3 + m_sat*G*(u(14,1)-u(20,1))/d_mercury_sat^3;
udot(24,1) = m_sun*G*(u(9,1)-u(21,1))/d_mercury_sun^3 + m_earth*G*(u(3,1)-u(21,1))/d_mercury_earth^3 + m_sat*G*(u(15,1)-u(21,1))/d_mercury_sat^3;
end
I want to find Orientation, MajorAxisLengthand MinorAxisLength of contour which is plotted with below code.
clear
[x1 , x2] = meshgrid(linspace(-10,10,100),linspace(-10,10,100));
mu = [1,3];
sigm = [2,0;0,2];
xx_size = length(mu);
tem_matrix = ones(size(x1));
x_mesh= cell(1,xx_size);
for i = 1 : xx_size
x_mesh{i} = tem_matrix * mu(i);
end
x_mesh= {x1,x2};
temp_mesh = [];
for i = 1 : xx_size
temp_mesh = [temp_mesh x_mesh{i}(:)];
end
Z = mvnpdf(temp_mesh,mu,sigm);
z_plat = reshape(Z,size(x1));
figure;contour(x1, x2, z_plat,3, 'LineWidth', 2,'color','m');
% regionprops(z_plat,'Centroid','Orientation','MajorAxisLength','MinorAxisLength');
In my opinion, I may have to use regionprops command but I don't know how to do this. I want to find direction of axis of contour and plot something like this
How can I do this task? Thanks very much for your help
Rather than trying to process the graphical output of contour, I would instead recommend using contourc to compute the ContourMatrix and then use the x/y points to estimate the major and minor axes lengths as well as the orientation (for this I used this file exchange submission)
That would look something like the following. Note that I have modified the inputs to contourc as the first two inputs should be the vector form and not the output of meshgrid.
% Compute the three contours for your data
contourmatrix = contourc(linspace(-10,10,100), linspace(-10,10,100), z_plat, 3);
% Create a "pointer" to keep track of where we are in the output
start = 1;
count = 1;
% Now loop through each contour
while start < size(contourmatrix, 2)
value = contourmatrix(1, start);
nPoints = contourmatrix(2, start);
contour_points = contourmatrix(:, start + (1:nPoints));
% Now fit an ellipse using the file exchange
ellipsedata(count) = fit_ellipse(contour_points(1,:), contour_points(2,:));
% Increment the start pointer
start = start + nPoints + 1;
count = count + 1;
end
orientations = [ellipsedata.phi];
% 0 0 0
major_length = [ellipsedata.long_axis];
% 4.7175 3.3380 2.1539
minor_length = [ellipsedata.short_axis];
% 4.7172 3.3378 2.1532
As you can see, the contours are actually basically circles and therefore the orientation is zero and the major and minor axis lengths are almost equal. The reason that they look like ellipses in your post is because your x and y axes are scaled differently. To fix this, you can call axis equal
figure;contour(x1, x2, z_plat,3, 'LineWidth', 2,'color','m');
axis equal
Thank you #Suever. It help me to do my idea.
I add some line to code:
clear
[X1 , X2] = meshgrid(linspace(-10,10,100),linspace(-10,10,100));
mu = [-1,0];
a = [3,2;1,4];
a = a * a';
sigm = a;
xx_size = length(mu);
tem_matrix = ones(size(X1));
x_mesh= cell(1,xx_size);
for i = 1 : xx_size
x_mesh{i} = tem_matrix * mu(i);
end
x_mesh= {X1,X2};
temp_mesh = [];
for i = 1 : xx_size
temp_mesh = [temp_mesh x_mesh{i}(:)];
end
Z = mvnpdf(temp_mesh,mu,sigm);
z_plat = reshape(Z,size(X1));
figure;contour(X1, X2, z_plat,3, 'LineWidth', 2,'color','m');
hold on;
% Compute the three contours for your data
contourmatrix = contourc(linspace(-10,10,100), linspace(-10,10,100), z_plat, 3);
% Create a "pointer" to keep track of where we are in the output
start = 1;
count = 1;
% Now loop through each contour
while start < size(contourmatrix, 2)
value = contourmatrix(1, start);
nPoints = contourmatrix(2, start);
contour_points = contourmatrix(:, start + (1:nPoints));
% Now fit an ellipse using the file exchange
ellipsedata(count) = fit_ellipse(contour_points(1,:), contour_points(2,:));
% Increment the start pointer
start = start + nPoints + 1;
count = count + 1;
end
orientations = [ellipsedata.phi];
major_length = [ellipsedata.long_axis];
minor_length = [ellipsedata.short_axis];
tet = orientations(1);
x1 = mu(1);
y1 = mu(2);
a = sin(tet) * sqrt(major_length(1));
b = cos(tet) * sqrt(major_length(1));
x2 = x1 + a;
y2 = y1 + b;
line([x1, x2], [y1, y2],'linewidth',2);
tet = ( pi/2 + orientations(1) );
a = sin(tet) * sqrt(minor_length(1));
b = cos(tet) * sqrt(minor_length(1));
x2 = x1 + a;
y2 = y1 + b;
line([x1, x2], [y1, y2],'linewidth',2);