plotting eigenvector in Matlab - matlab

I'm trying to plot a the eigenvectors of a 2D Dataset, for that I'm trying to use the quiver function in Matlab, here's what I've done so far :
% generating 2D data
clear ;
s = [2 2]
set = randn(200,1);
x = normrnd(s(1).*set,1)+3
y = normrnd(s(1).*set,1)+2
x_0 = mean(x)
y_0 = mean (y)
c = linspace(1,100,length(x)); % color
scatter(x,y,100,c,'filled')
xlabel('1st Feature : x')
ylabel('2nd Feature : y')
title('2D dataset')
grid on
% gettign the covariance matrix
covariance = cov([x,y])
% getting the eigenvalues and the eigenwert
[eigen_vector, eigen_values] = eig(covariance)
eigen_value_1 = eigen_values(1,1)
eigen_vector_1 =eigen_vector(:,1)
eigen_value_2 = eigen_values(2,2)
eigen_vector_2 =eigen_vector(:,2)
% ploting the eigenvectors !
hold on
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1))
My problem is the last line, I get the following error :
Error using quiver (line 44)
The size of Y must match the size of U or the number of rows of U.
It seems that I'm missing a size here but I can't figure out where!
thanks in advance for any hint

As the error says, X and Y parameters must have, respectively, the same size of U and V parameters. If you change the last part of your code:
% ploting the eigenvectors !
hold on
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1))
as follows:
x_0 = repmat(x_0,size(eigen_vector_2,1),1);
y_0 = repmat(x_0,size(eigen_vector_1,1),1);
% ploting the eigenvectors !
hold on;
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1));
hold off;
your script should properly work.

Related

Error using stem X must be same length as Y

im trying to find the even and odd part of the x array but it returns me error using stem, X must be same length as Y this is my code in matlab
close all;
clear all;
clc;
n1 = -5:1:5;
AM = 19390;
x = [1,9,3,9,0,1,1,9,3,9,0];
fun(x,n1);
function [sima,xr] = fun(t,x)
x_reverse = fliplr(x);% time reversal
sima = 0.5*(x + x_reverse); %even component
xr = 0.5*(x - x_reverse); %odd component
subplot(3,1,1);
stem(t,x);
title('Your signal x')
subplot(3,1,2);
stem(t,sima);
title('Even part');
subplot(3,1,3);
stem(t,xr);
title('Odd part');
end
the inputs of fun are reversed.
where you write
fun(x,n1)
you should have
fun(n1,x)
this or reverse the order of each reference and value vectors for each stem inside fun.

How to plot a covariance matrix on a 2D plot in MATLAB?

In MATLAB there is a function called cov. If I insert a matrix X into cov like this cov(X), then cov will return a square matrix of covariance.
My question is very simple:
How can I, with MATLAB, plot that matrix cov(X) onto a 2D plot like this.
I can see a lot of covariance matrix plots at Google. But how do they create them?
My best guess is that you're trying to add the principal components to the plot. To do that, you could do something like this.
%% generate data points
S_tru = [2 1; 1 1];
N = 1000;
%% compute mean, covariance, principal components
X = mvnrnd([0,0],S_tru,N);
mu = mean(X);
S = cov(X);
[U,D] = eig(S);
%% specify base points/directions for arrows
base = [mu;mu];
vecs = sqrt(D)*U';
vecs = 2 * vecs;
%% plot
plot(X(:,1),X(:,2), 'r.')
axis equal
hold on
quiver(base(:,1),base(:,2),vecs(:,1),vecs(:,2),'blue','LineWidth',2)
Resulting graph:

Constrained linear least squares not fitting data

I am trying to fit a 3D surface polynomial of n-degrees to some data points in 3D space. My system requires the surface to be monotonically increasing in the area of interest, that is the partial derivatives must be non-negative. This can be achieved using Matlab's built in lsqlin function.
So here's what I've done to try and achieve this:
I have a function that takes in four parameters;
x1 and x2 are my explanatory variables and y is my dependent variable. Finally, I can specify order of polynomial fit. First I build the design matrix A using data from x1 and x2 and the degree of fit I want. Next I build the matrix D that is my container for the partial derivatives of my datapoints. NOTE: the matrix D is double the length of matrix A since all datapoints must be differentiated with respect to both x1 and x2. I specify that Dx >= 0 by setting b to be zeroes.
Finally, I call lsqlin. I use "-D" since Matlab defines the function as Dx <= b.
function w_mono = monotone_surface_fit(x1, x2, y, order_fit)
% Initialize design matrix
A = zeros(length(x1), 2*order_fit+2);
% Adjusting for bias term
A(:,1) = ones(length(x1),1);
% Building design matrix
for i = 2:order_fit+1
A(:,(i-1)*2:(i-1)*2+1) = [x1.^(i-1), x2.^(i-1)];
end
% Initialize matrix containing derivative constraint.
% NOTE: Partial derivatives must be non-negative
D = zeros(2*length(y), 2*order_fit+1);
% Filling matrix that holds constraints for partial derivatives
% NOTE: Matrix D will be double length of A since all data points will have a partial derivative constraint in both x1 and x2 directions.
for i = 2:order_fit+1
D(:,(i-1)*2:(i-1)*2+1) = [(i-1)*x1.^(i-2), zeros(length(x2),1); ...
zeros(length(x1),1), (i-1)*x2.^(i-2)];
end
% Limit of derivatives
b = zeros(2*length(y), 1);
% Constrained LSQ fit
options = optimoptions('lsqlin','Algorithm','interior-point');
% Final weights of polynomial
w_mono = lsqlin(A,y,-D,b,[],[],[],[],[], options);
end
So now I get some weights out, but unfortunately they do not at all capture the structure of the data. I've attached an image so you can just how bad it looks. .
I'll give you my plotting script with some dummy data, so you can try it.
%% Plot different order polynomials to data with constraints
x1 = [-5;12;4;9;18;-1;-8;13;0;7;-5;-8;-6;14;-1;1;9;14;12;1;-5;9;-10;-2;9;7;-1;19;-7;12;-6;3;14;0;-8;6;-2;-7;10;4;-5;-7;-4;-6;-1;18;5;-3;3;10];
x2 = [81.25;61;73;61.75;54.5;72.25;80;56.75;78;64.25;85.25;86;80.5;61.5;79.25;76.75;60.75;54.5;62;75.75;80.25;67.75;86.5;81.5;62.75;66.25;78.25;49.25;82.75;56;84.5;71.25;58.5;77;82;70.5;81.5;80.75;64.5;68;78.25;79.75;81;82.5;79.25;49.5;64.75;77.75;70.25;64.5];
y = [-6.52857142857143;-1.04736842105263;-5.18750000000000;-3.33157894736842;-0.117894736842105;-3.58571428571429;-5.61428571428572;0;-4.47142857142857;-1.75438596491228;-7.30555555555556;-8.82222222222222;-5.50000000000000;-2.95438596491228;-5.78571428571429;-5.15714285714286;-1.22631578947368;-0.340350877192983;-0.142105263157895;-2.98571428571429;-4.35714285714286;-0.963157894736842;-9.06666666666667;-4.27142857142857;-3.43684210526316;-3.97894736842105;-6.61428571428572;0;-4.98571428571429;-0.573684210526316;-8.22500000000000;-3.01428571428571;-0.691228070175439;-6.30000000000000;-6.95714285714286;-2.57232142857143;-5.27142857142857;-7.64285714285714;-2.54035087719298;-3.45438596491228;-5.01428571428571;-7.47142857142857;-5.38571428571429;-4.84285714285714;-6.78571428571429;0;-0.973684210526316;-4.72857142857143;-2.84285714285714;-2.54035087719298];
% Used to plot the surface in all points in the grid
X1 = meshgrid(-10:1:20);
X2 = flipud(meshgrid(30:2:90).');
figure;
for i = 1:4
w_mono = monotone_surface_fit(x1, x2, y, i);
y_nr = w_mono(1)*ones(size(X1)) + w_mono(2)*ones(size(X2));
for j = 1:i
y_nr = w_mono(j*2)*X1.^j + w_mono(j*2+1)*X2.^j;
end
subplot(2,2,i);
scatter3(x1, x2, y); hold on;
axis tight;
mesh(X1, X2, y_nr);
set(gca, 'ZDir','reverse');
xlabel('x1'); ylabel('x2');
zlabel('y');
% zlim([-10 0])
end
I think it may have something to do with the fact that I haven't specified anything about the region of interest, but really I don't know. Thanks in advance for any help.
Alright I figured it out.
The main problem was simply an error in the plotting script. The value of y_nr should be updated and not overwritten in the loop.
Also I figured out that the second derivative should be monotonically decreasing. Here's the updated code if anybody is interested.
%% Plot different order polynomials to data with constraints
x1 = [-5;12;4;9;18;-1;-8;13;0;7;-5;-8;-6;14;-1;1;9;14;12;1;-5;9;-10;-2;9;7;-1;19;-7;12;-6;3;14;0;-8;6;-2;-7;10;4;-5;-7;-4;-6;-1;18;5;-3;3;10];
x2 = [81.25;61;73;61.75;54.5;72.25;80;56.75;78;64.25;85.25;86;80.5;61.5;79.25;76.75;60.75;54.5;62;75.75;80.25;67.75;86.5;81.5;62.75;66.25;78.25;49.25;82.75;56;84.5;71.25;58.5;77;82;70.5;81.5;80.75;64.5;68;78.25;79.75;81;82.5;79.25;49.5;64.75;77.75;70.25;64.5];
y = [-6.52857142857143;-1.04736842105263;-5.18750000000000;-3.33157894736842;-0.117894736842105;-3.58571428571429;-5.61428571428572;0;-4.47142857142857;-1.75438596491228;-7.30555555555556;-8.82222222222222;-5.50000000000000;-2.95438596491228;-5.78571428571429;-5.15714285714286;-1.22631578947368;-0.340350877192983;-0.142105263157895;-2.98571428571429;-4.35714285714286;-0.963157894736842;-9.06666666666667;-4.27142857142857;-3.43684210526316;-3.97894736842105;-6.61428571428572;0;-4.98571428571429;-0.573684210526316;-8.22500000000000;-3.01428571428571;-0.691228070175439;-6.30000000000000;-6.95714285714286;-2.57232142857143;-5.27142857142857;-7.64285714285714;-2.54035087719298;-3.45438596491228;-5.01428571428571;-7.47142857142857;-5.38571428571429;-4.84285714285714;-6.78571428571429;0;-0.973684210526316;-4.72857142857143;-2.84285714285714;-2.54035087719298];
% Used to plot the surface in all points in the grid
X1 = meshgrid(-10:1:20);
X2 = flipud(meshgrid(30:2:90).');
figure;
for i = 1:4
w_mono = monotone_surface_fit(x1, x2, y, i);
% NOTE: Should only have 1 bias term
y_nr = w_mono(1)*ones(size(X1));
for j = 1:i
y_nr = y_nr + w_mono(j*2)*X1.^j + w_mono(j*2+1)*X2.^j;
end
subplot(2,2,i);
scatter3(x1, x2, y); hold on;
axis tight;
mesh(X1, X2, y_nr);
set(gca, 'ZDir','reverse');
xlabel('x1'); ylabel('x2');
zlabel('y');
% zlim([-10 0])
end
And here's the updated function
function [w_mono, w] = monotone_surface_fit(x1, x2, y, order_fit)
% Initialize design matrix
A = zeros(length(x1), 2*order_fit+1);
% Adjusting for bias term
A(:,1) = ones(length(x1),1);
% Building design matrix
for i = 2:order_fit+1
A(:,(i-1)*2:(i-1)*2+1) = [x1.^(i-1), x2.^(i-1)];
end
% Initialize matrix containing derivative constraint.
% NOTE: Partial derivatives must be non-negative
D = zeros(2*length(y), 2*order_fit+1);
for i = 2:order_fit+1
D(:,(i-1)*2:(i-1)*2+1) = [(i-1)*x1.^(i-2), zeros(length(x2),1); ...
zeros(length(x1),1), -(i-1)*x2.^(i-2)];
end
% Limit of derivatives
b = zeros(2*length(y), 1);
% Constrained LSQ fit
options = optimoptions('lsqlin','Algorithm','active-set');
w_mono = lsqlin(A,y,-D,b,[],[],[],[],[], options);
w = lsqlin(A,y);
end
Finally a plot of the fitting (Have used a new simulation, but fit also works on given dummy data).

plotting the Eigenvectors correctly in Matlab

I'm trying to plot the caculated Eigenvectors of 2D dataset, here the script I've wrote for that:
clear ;
s = [2 2]
set = randn(200,1);
x = normrnd(s(1).*set,1)+3
x = zscore(x) % Standardize
y = normrnd(s(1).*set,1)+2
y= zscore(y)%Standardize
x_0 = mean(x)
y_0 = mean (y)
c = linspace(1,100,length(x)); % color
scatter(x,y,100,c,'filled')
xlabel('1st Feature : x')
ylabel('2nd Feature : y')
title('2D_dataset')
grid on
% gettign the covariance matrix
covariance = cov([x,y])
% getting the eigenvalues and the eigenwert
[eigen_vector, eigen_values] = eig(covariance)
eigen_value_1 = eigen_values(1,1)
eigen_vector_1 =eigen_vector(:,1)
eigen_value_2 = eigen_values(2,2)
eigen_vector_2 =eigen_vector(:,2)
% ploting the eigenvectors !
hold on
x_0 = repmat(x_0,size(eigen_vector_2,1),1);
y_0 = repmat(y_0,size(eigen_vector_1,1),1);
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1),'-r','LineWidth',5)
and here is the result I'm getting:
I've double checked the math, the values are correct, but the plot is a mess !
Any idea what I'm missing in the plot of the 2 vectors ?
thanks in advance !
In your code, replace this part:
covariance = cov([x,y])
% getting the eigenvalues and the eigenwert
[eigen_vector, eigen_values] = eig(covariance)
eigen_value_1 = eigen_values(1,1)
eigen_vector_1 =eigen_vector(:,1)
eigen_value_2 = eigen_values(2,2)
eigen_vector_2 =eigen_vector(:,2)
% ploting the eigenvectors !
hold on
x_0 = repmat(x_0,size(eigen_vector_2,1),1);
y_0 = repmat(y_0,size(eigen_vector_1,1),1);
quiver(x_0, y_0,eigen_vector_2*(eigen_value_2),eigen_vector_1*(eigen_value_1),'-r','LineWidth',5)
with the following code:
covariance = cov([x,y]);
[eigen_vector, eigen_values] = eig(covariance);
eigen_vector_1 = eigen_vector(:,1);
eigen_vector_2 = eigen_vector(:,2);
d = sqrt(diag(eigen_values));
hold on;
quiver(x_0,y_0,eigen_vector(1,2),eigen_vector(2,2),d(2),'k','LineWidth',5);
quiver(x_0,y_0,eigen_vector(1,1),eigen_vector(2,1),d(1),'r','LineWidth',5);
hold off;
Does this produces what you are looking for? It looks much more coherent to me...
You are plotting the two components of one eigenvector as the x component of two vectors, and the other eigenvector as the y components.
[eigen_vector, eigen_values] = eig(covariance)
eigen_x = eigen_vector(1,:);
eigen_y = eigen_vector(2,:);
scale = diag(eigen_vector)'; % not sure what the output orientation is
% ploting the eigenvectors !
hold on
x_0 = repmat(x_0,size(eigen_vector_2,1),1);
y_0 = repmat(y_0,size(eigen_vector_1,1),1);
quiver(x_0, y_0,eigen_x.*scale,eigen_y.*scale,'-r')
Actually, because they are orthonormal, slicing the matrix the other way does not change much. But your scaling is changing the angles of the vectors, not just thier length, because of what I mention above.

Matlab : x v/s y plot

I want to plot a function y=1-exp(c) ,where as the range of x is defined. The plot is to be between x and the function y. The plot just shows just 1 point instead of showing a series of points exponentially.I am new in Matlab.Sp,please help me where I am going wrong Here is the code:
for x = -10:0.25:10
if(x>0)
c=-6*x;
m=exp(c);
y = 1-m
end
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')
end
This should do it:
x = -10:0.25:10; % define the x vector
c= -5*x.*(x>0); % using a logical condition the 'if' is avoided
y = 1-exp(c); % calc y given c
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')
no 'for' loop or 'if' needed...
Your problem is the for loop. It is resetting the value of y and re-ploting that one point each loop. You don't need that loop at all. This code will do the trick for y = 1-exp(A*x)
Edit (2012-10-30) OP says y is zero for x<=0. #Nate's code in the answer above is probably best, but here I use logical indexing to show a different way to do the same thing.
x = -10:0.25:10; % <vector>
y = zeros(size(x)); % prealocate y with zeros and make it the same size as x
y(x>0) = 1 - exp(-5*x(x>0)); % only calculate y values for x>0
plot(x,y,'o')
xlabel('x')
ylabel('y')
title('Plot')