Plotting axis of greatest variance

3 views (last 30 days)
Laura T
Laura T on 10 Dec 2021
Answered: William Rose on 1 Feb 2022
Hi Guys,
I am trying to plot the axis that has the greatest variance ontop of a graph i have previously coded for (eg from figure 1) as a new graph (eg figure 2). How do i do this?
And to plot an axis that is perpendicular to this axis ive just added?
TIA

Answers (1)

William Rose
William Rose on 1 Feb 2022
I am changing my comment to an answer, which is what i had intended.
Let's start by generating some data.
N=100;
theta=pi/6;
x0=3*randn(1,N)+2;
y0=randn(1,N);
x=cos(theta)*x0-sin(theta)*y0;
y=sin(theta)*x0+cos(theta)*y0;
figure;
subplot(2,1,1), plot(x,y,'rx'); axis equal; grid on; hold on
Now find principal axes and plot them.
[V,D]=eig(cov([x',y'])); %columns of V are directions of principal axes
%they are guaranteed to be perpendcular
m1=V(2,1)/V(1,1); %slope of axis 1
b1=mean(y)-m1*mean(x); %intercept of axis 1
m2=V(2,2)/V(1,2);
b2=mean(y)-m2*mean(x);
axisx=[min(x),max(x)]; %x values, for plotting the axes
axis1y=m1*axisx+b1; %y values of axis 1
axis2y=m2*axisx+b2;
plot(axisx,axis1y,'-r',axisx,axis2y,'-r');
xlim(axisx);ylim([min(y),max(y)]);
Next, plot the data in the new coordinate system defined by the axes shown above.
x1=x-mean(x);
y1=y-mean(y);
if D(1,1)>D(2,2) %if column 1 of V is axis of max variation
theta2=atan(V(2,1)/V(1,1));
else %else column 2 of V is axis of max variation
theta2=atan(V(2,2)/V(1,2));
end
x2=cos(theta2)*x1+sin(theta2)*y1;
y2=-sin(theta2)*x1+cos(theta2)*y1;
subplot(2,1,2), plot(x2,y2,'bx');
axis equal; grid on
Good luck.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!