plotting the Eigenvectors correctly in Matlab - 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.

Related

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).

Plot quiver polar coordinates

I want to plot the field distribution inside a circular structure with radius a.
What I expect to see are circular arrows that from the centre 0 go toward a in the radial direction like this
but I'm obtaining something far from this result. I wrote this
x_np = besselzero(n, p, 1); %toolbox from mathworks.com for the roots
R = 0.1:1:a; PHI = 0:pi/180:2*pi;
for r = 1:size(R,2)
for phi = 1:size(PHI,2)
u_R(r,phi) = -1/2*((besselj(n-1,x_np*R(1,r)/a)-besselj(n+1,x_np*R(1,r)/a))/a)*cos(n*PHI(1,phi));
u_PHI(r,phi) = n*(besselj(n,x_np*R(1,r)/a)/(x_np*R(1,r)))*sin(PHI(1,phi));
end
end
[X,Y] = meshgrid(R);
quiver(X,Y,u_R,u_PHI)
where u_R is supposed to be the radial component and u_PHI the angular component. Supposing the formulas that I'm writing are correct, do you think there is a problem with for cycles? Plus, since R and PHI are not with the same dimension (in this case R is 1x20 and PHI 1X361) I also get the error
The size of X must match the size of U or the number of columns of U.
that I hope to solve it if I figure out which is the problem with the cycles.
This is the plot that I get
The problem has to do with a difference in co-ordinate systems.
quiver expects inputs in a Cartesian co-ordinate system.
The rest of your code seems to be expressed in a polar co-ordinate system.
Here's a snippet that should do what you want. The initial parameters section is filled in with random values because I don't have besselzero or the other details of your problem.
% Define initial parameters
x_np = 3;
a = 1;
n = 1;
% Set up domain (Cartesian)
x = -a:0.1:a;
y = -a:0.1:a;
[X, Y] = meshgrid(x, y);
% Allocate output
U = zeros(size(X));
V = zeros(size(X));
% Loop over each point in domain
for ii = 1:length(x)
for jj = 1:length(y)
% Compute polar representation
r = norm([X(ii,jj), Y(ii,jj)]);
phi = atan2(Y(ii,jj), X(ii,jj));
% Compute polar unit vectors
rhat = [cos(phi); sin(phi)];
phihat = [-sin(phi); cos(phi)];
% Compute output (in polar co-ordinates)
u_R = -1/2*((besselj(n-1, x_np*r/a)-besselj(n+1, x_np*r/a))/a)*cos(n*phi);
u_PHI = n*(besselj(n, x_np*r/a)/(x_np*r))*sin(phi);
% Transform output to Cartesian co-ordinates
U(ii,jj) = u_R*rhat(1) + u_PHI*phihat(1);
V(ii,jj) = u_R*rhat(2) + u_PHI*phihat(2);
end
end
% Generate quiver plot
quiver(X, Y, U, V);

plotting eigenvector in 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.

Two plots of same wave in MatLab, but plot created after transforming to polar coordinates is distorded?

I have created some MatLab code that plots a plane wave using two different expressions that give the same plane wave. The first expression is in Cartesian coordinates and works fine. However, the second expression is in polar coordinates and when I calculate the plane wave in this case, the plot is distorted. Both plots should look the same. So what am I doing wrong in transforming to/from polar coordinates?
function Plot_Plane_wave()
clc
clear all
close all
%% Step 0. Input paramaters and derived parameters.
alpha = 0*pi/4; % angle of incidence
k = 1; % wavenumber
wavelength = 2*pi/k; % wavelength
%% Step 1. Define various equivalent versions of the incident wave.
f_u_inc_1 = #(alpha,x,y) exp(1i*k*(x*cos(alpha)+y*sin(alpha)));
f_u_inc_2 = #(alpha,r,theta) exp(1i*k*r*cos(theta-alpha));
%% Step 2. Evaluate the incident wave on a grid.
% Grid for field
gridMax = 10;
gridN = 2^3;
g1 = linspace(-gridMax, gridMax, gridN);
g2 = g1;
[x,y] = meshgrid(g1, g2);
[theta,r] = cart2pol(x,y);
u_inc_1 = f_u_inc_1(alpha,x,y);
u_inc_2 = 0*x;
for ir=1:gridN
rVal = r(ir);
for itheta=1:gridN
thetaVal = theta(itheta);
u_inc_2(ir,itheta) = f_u_inc_2(alpha,rVal,thetaVal);
end
end
%% Step 3. Plot the incident wave.
figure(1);
subplot(2,2,1)
imagesc(g1(1,:), g1(1,:), real(u_inc_1));
hGCA = gca; set(hGCA, 'YDir', 'normal');
subplot(2,2,2)
imagesc(g1(1,:), g1(1,:), real(u_inc_2));
hGCA = gca; set(hGCA, 'YDir', 'normal');
end
Your mistake is that your loop is only going through the first gridN values of r and theta. Instead you want to step through the indices of ix and iy and pull out the rVal and thetaVal of the matrices r and theta.
You can change your loop to
for ix=1:gridN
for iy=1:gridN
rVal = r(ix,iy); % Was equivalent to r(ix) outside inner loop
thetaVal = theta(ix,iy); % Was equivalent to theta(iy)
u_inc_2(ix,iy) = f_u_inc_2(alpha,rVal,thetaVal);
end
end
which gives the expected graphs.
Alternatively you can simplify your code by feeding matrices in to your inline functions. To do this you would have to use an elementwise product .* instead of a matrix multiplication * in f_u_inc_2:
alpha = 0*pi/4;
k = 1;
wavelength = 2*pi/k;
f_1 = #(alpha,x,y) exp(1i*k*(x*cos(alpha)+y*sin(alpha)));
f_2 = #(alpha,r,theta) exp(1i*k*r.*cos(theta-alpha));
% Change v
f_old = #(alpha,r,theta) exp(1i*k*r *cos(theta-alpha));
gridMax = 10;
gridN = 2^3;
[x,y] = meshgrid(linspace(-gridMax, gridMax, gridN));
[theta,r] = cart2pol(x,y);
subplot(1,3,1)
contourf(x,y,real(f_1(alpha,x,y)));
title 'Cartesian'
subplot(1,3,2)
contourf(x,y,real(f_2(alpha,r,theta)));
title 'Polar'
subplot(1,3,3)
contourf(x,y,real(f_old(alpha,r,theta)));
title 'Wrong'

Providing correct inputs for surface curvature calculation

I want to calculate the mean and Gaussian curvatures of some points in a point cloud.
I have x,y,z, that are coordinates and are 1d arrays. I want to use the below code src but in the input parameters X, Y and Z are 2d arrays, I don't know what means that, and how I can calculate 2d arrays corresponding to them.
function [K,H,Pmax,Pmin] = surfature(X,Y,Z),
% SURFATURE - COMPUTE GAUSSIAN AND MEAN CURVATURES OF A SURFACE
% [K,H] = SURFATURE(X,Y,Z), WHERE X,Y,Z ARE 2D ARRAYS OF POINTS ON THE
% SURFACE. K AND H ARE THE GAUSSIAN AND MEAN CURVATURES, RESPECTIVELY.
% SURFATURE RETURNS 2 ADDITIONAL ARGUMENTS,
% [K,H,Pmax,Pmin] = SURFATURE(...), WHERE Pmax AND Pmin ARE THE MINIMUM
% AND MAXIMUM CURVATURES AT EACH POINT, RESPECTIVELY.
% First Derivatives
[Xu,Xv] = gradient(X);
[Yu,Yv] = gradient(Y);
[Zu,Zv] = gradient(Z);
% Second Derivatives
[Xuu,Xuv] = gradient(Xu);
[Yuu,Yuv] = gradient(Yu);
[Zuu,Zuv] = gradient(Zu);
[Xuv,Xvv] = gradient(Xv);
[Yuv,Yvv] = gradient(Yv);
[Zuv,Zvv] = gradient(Zv);
% Reshape 2D Arrays into Vectors
Xu = Xu(:); Yu = Yu(:); Zu = Zu(:);
Xv = Xv(:); Yv = Yv(:); Zv = Zv(:);
Xuu = Xuu(:); Yuu = Yuu(:); Zuu = Zuu(:);
Xuv = Xuv(:); Yuv = Yuv(:); Zuv = Zuv(:);
Xvv = Xvv(:); Yvv = Yvv(:); Zvv = Zvv(:);
Xu = [Xu Yu Zu];
Xv = [Xv Yv Zv];
Xuu = [Xuu Yuu Zuu];
Xuv = [Xuv Yuv Zuv];
Xvv = [Xvv Yvv Zvv];
% First fundamental Coeffecients of the surface (E,F,G)
E = dot(Xu,Xu,2);
F = dot(Xu,Xv,2);
G = dot(Xv,Xv,2);
m = cross(Xu,Xv,2);
p = sqrt(dot(m,m,2));
n = m./[p p p];
% Second fundamental Coeffecients of the surface (L,M,N)
L = dot(Xuu,n,2);
M = dot(Xuv,n,2);
N = dot(Xvv,n,2);
[s,t] = size(Z);
% Gaussian Curvature
K = (L.*N - M.^2)./(E.*G - F.^2);
K = reshape(K,s,t);
% Mean Curvature
H = (E.*N + G.*L - 2.*F.*M)./(2*(E.*G - F.^2));
H = reshape(H,s,t);
% Principal Curvatures
Pmax = H + sqrt(H.^2 - K);
Pmin = H - sqrt(H.^2 - K);
You have ways to convert your x,y,z data to surface matrices/ 2D arrays. Way depends on, how and what your data is.
Structured grid data:
(i). If your x,y,z corresponds to a structured grid, then you can straight a way get unique values of x,y which gives number of points along (nx,ny) along x and y axes respectively. With this (nx,ny), you need to reshape x,y,z data into matrices X,Y,Z respectively and use your function.
(ii). If you are not okay with reshaping, you can get min and max values of x,y make your own grid using meshgrid and do interpolation using griddata.
Unstructured grid data: If your data is unstructured/ scattered, get min and max, make your grid using meshgrid and do interpolation using griddata , scatteredInterpolant.
Also have a look in the following links:
https://in.mathworks.com/matlabcentral/fileexchange/56533-xyz2grd
https://in.mathworks.com/matlabcentral/fileexchange/56414-xyz-file-functions