I want to store a randomly generated set of co-ordinates in Matlab using a 2D array which should look like this
array = X Y
t1 x1 y1
t2 x2 y2
t3 x3 y3
... ...
tn xn yn
where ti is the i-th point in a 2D plane and has co-ordinates (xi,yi)
After creating this array, I want to calculate the Euclidean distance between ti and tj for all 1≤i,j≤n. How can this be achieved in Matlab?
N = 10; % # of points
X = rand(N, 1); % random coordinates
Y = rand(N, 1);
[X1, X2] = meshgrid(X);
[Y1, Y2] = meshgrid(Y);
d = sqrt((X1-X2).^2 + (Y1-Y2).^2); % pairwise distance in NxN, diag 0
The upper or lower triangle should contain the distance from
pdist([X Y]) % vector, not a matrix
You can use bsxfun to replicate operations over arrays.
N = 10;
p = rand(N,2); % coordinates
d = sqrt(bsxfun(#minus,p(:,1),p(:,1)').^2+bsxfun(#minus,p(:,2),p(:,2)').^2);
The first bsxfun replicates the X coords in p(:,1) and p(:,1)' into NxN matrices by expanding the singleton dimension and the result is the subtraction of these matrices. Similarly, the second bsxfun. The rest is just array operations to square, sum and square root.
If you happen to have the statistics toolbox you can use pdist, but this gives a row vector corresponding to the lower triangle of d.
Related
I have two arrays
x = [0 9.8312 77.1256 117.9810 99.9979];
y = [0 2.7545 4.0433 5.3763 5.0504];
figure; plot(x, y)
I want to make more samples of x and y then I interpolated both arrays. I tried this code
xi =min(x):.1:max(x);
yi = interp1(x,y,xi);
figure; plot(xi, yi)
but the trajectory is not same as previous plot. Its because the xi is not fluctuating same as x. How should I interpolate both arrays with same trajectory as original one?
This is an issue because when interpolating, MATLAB is going to ignore the order that you feed in the points and instead just sort them based upon their x location.
Rather than interpolating in x/y coordinates, you can instead use a parameter which represents the cumulative arc length of the line segments and use that to interpolate both the x and y coordinates. This will provide you with an interpolant that respects the order and guarantees monotonicity even for multiple values at the same x coordinate.
% Compute the distance between all points.
distances = sqrt(diff(x).^2 + diff(y).^2);
% Compute the cumulative arclength
t = cumsum([0 distances]);
% Determine the arclengths to interpolate at
tt = linspace(t(1), t(end), 1000);
% Now interpolate x and y at these locations
xi = interp1(t, x, tt);
yi = interp1(t, y, tt);
I am trying to graph a surface with a diagonal matrix, the equation I am trying graph is f = x^TDx, x is a 2 by 1 vector and D is a 2 by 2 matrix.
Here is what have so far, but I keep getting error.
x = linspace(-10,10);
y = linspace(-10,10);
[X,Y] = meshgrid(x,y);
D = [1 0; 0 1];
f = #(x,y) [x,y]*D*[x,y].'; % [x,y] is 1 by 2
contour (X,Y,f(X,Y))
Can someone tell me how to get rid of the error? Thanks
Since x and y have the same length, your diagonal matrix D must be a square matrix of size n x n, with n equal to two times the length of your x or y vectors. The reason why you need to multiply the length by two is because the operation [x,y] concatenates the arrays horizontally thus duplicating one of the dimensions.
In this example D is the Identity matrix. See eye for more information.
x = linspace(-10,10); % x is 1x100
y = linspace(-10,10); % y is 1x100
[X,Y] = meshgrid(x,y); % X is 100x100 and Y is 100x100
D = eye(2*numel(x)); % D is 2*100x2*100 = 200x200
f = #(x,y) [x,y]*D*[x,y].'; % [X,Y] is 100x200 and [X,Y].' is 200x100
contour (X,Y,f(X,Y))
If you want D to be a random diagonal matrix, you can accomplish this combining diag with one of the Random Number Generation functions available, like for example randn.
On the previous example, replace D with the following instruction:
D = diag(randn(1,2*numel(x)));
You can also give the coefficients you choose to the diagonal matrix. To do so, you will need to create the vector of coefficients manually, making sure that it has the adequate length, so that it satisfies the conditions explained at the beginning of this post.
Try now replacing D with the following instructions:
v = 1:2*numel(x); % vector of coefficients: v = [1 2 ... 200]
D = diag(v);
How can I plot the vector w with the projected data onto this vector?
Here is the code - and my trials to plot the weight vector with y1 and y2.
x1=[1 2;2 3;3 3;4 5;5 5] % the first class 5 observations
x2=[1 0;2 1;3 1;3 2;5 3;6 5]
m1 = mean(x1);
m2 = mean(x2);
m = m1 + m2;
d1=x1-repmat(m1,5,1);
d2=x2-repmat(m2,6,1);
c = 0.5.*m;
Sw1 = d1'*d1;
Sw2 = d2'*d2;
Sw = Sw1 + Sw2;
invSw = inv(Sw);
w= invSw*(m1-m2)' %this is my vector projected
scatter(x1(:,1), x1(:,2), 10, 'ro');
hold on;
scatter(x2(:,1), x2(:,2), 10,'bo');
%this is how i plot the decision boundary, but it doesn't seems correct.
quiver(c(1,1), c(1,2), 1, -w(1,1)/w(2,1));
quiver(c(1,1), c(1,2), -1, w(1,1)/w(2,1));
auxw= w/norm(w);
plot([0 auxw(1)], [0 auxw(2)])
hold off;
figure;
y1 = x1*w;
y2 = x2*w;
hist([y1' y2'])
You are very close. You've only calculated (or tried to calculate) the scalar projection or the amount of scale you apply to each vector in order to project each vector in x1 and x2 onto w though what you have is incomplete. If you recall from linear algebra, to determine the scalar projection between two vectors a and b, or the scalar projection of b onto a, the formula is:
Source: Oregon State Mathematics: Calculus for Undergraduates
In our case, a would be w and b would be each of the vectors seen in x1 and x2. I'm assuming each row of these matrices is a vector. The scalar projections are seen in y1 and y2. You need to compute the vector projection, which is defined as taking the scalar projections and multiplying by the unit vectors of a, or simply:
Source: Oregon State Mathematics: Calculus for Undergraduates
Therefore, the calculation of the scalar projections in y1 and y2 are incorrect. You have to multiply by the normalized vector w, then when you find these scalar projection values, you multiply each of these scalar values with the corresponding normalized vector w. However, plotting these all simultaneously on a graph will be confusing. You will have many lines that will overlap onto the original vector w so what I did was I looped through plotting w, a vector in either x1 or x2 and the corresponding projected vector. Each time we loop, we pause and show the data then clear the figure and start again.
As such, I've added and changed the following to your code.
%// Your data
w = [-0.7936; 0.8899];
x1 = [1 2; 2 3; 3 3; 4 5; 5 5];
x2 = [1 0; 2 1; 3 1; 3 2; 5 3; 6 5];
%// Compute scalar projection
auxw = w/norm(w);
s1 = x1*auxw;
s2 = x2*auxw; %// Change for correctness
%// Compute the vector projection
y1 = bsxfun(#times, s1, auxw.');
y2 = bsxfun(#times, s2, auxw.');
%// Place the original vectors and corresponding projections
%// in one matrix
y = [y1; y2];
x = [x1; x2];
%// Loop through and plot w, a point in either x1 or x2
%// and the corresponding projection
for ii = 1 : size(y,1)
plot([0 w(1)], [0 w(2)]);
hold on;
plot([0 y(ii,1)], [0 y(ii,2)], 'r');
plot([0 x(ii,1)], [0 x(ii,2)], 'g');
pause(0.5);
clf;
end
The function bsxfun allows us to multiply each vector in x1 and x2 by their corresponding scalar values. Specifically, it will take the vectors s1 and s2 and when we transpose auxw to be a 1 x 2 vector, we will create new matrices y1 and y2 where each row of either will compute the vector projections of x1 and x2 and place them into the rows of y1 and y2.
The loop at the end cycles through w, a vector in either x1 or x2 and the corresponding projected vector one at a time and we pause for 0.5 seconds each time to see what the results look like. The vector w is in blue, the projected vector is in green and the original vector from either x1 or x2 is in red.
We get these series of figures:
We can see that the red line, which is the projected vector from either x1 or x2 onto w. The green line is the original vector from either x1 or x2.
I intend to use Matlab to plot the probability distribution from stochastic process on its state space. The state space can be represented by the lower triangle of a 150x150 matrix. Please see the figure (a surf plot without mesh) for a probability distribution at a certain time point.
As we can see, there is a high degree of symmetry in the graph, but because it is plotted as a square matrix, it looks kind of weird. It we could transform the rectangle the plot would look perfect. My question is, how can I use Matlab to plot/transform the lower triangle portion as/to an equal-lateral triangle?
This function should do the job for you. If not, please let me know.
function matrix_lower_tri_to_surf(A)
%Displays lower triangle portion of matrix as an equilateral triangle
%Martin Stålberg, Uppsala University, 2013-07-12
%mast4461 at gmail
siz = size(A);
N = siz(1);
if ~(ndims(A)==2) || ~(N == siz(2))
error('Matrix must be square');
end
zeds = #(N) zeros(N*(N+1)/2,1); %for initializing coordinate vectors
x = zeds(N); %x coordinates
y = zeds(N); %y coordinates
z = zeds(N); %z coordinates, will remain zero
r = zeds(N); %row indices
c = zeds(N); %column indices
l = 0; %base index
xt = 1:N; %temporary x coordinates
yt = 1; %temporary y coordinates
for k = N:-1:1
ind = (1:k)+l; %coordinate indices
l = l+k; %update base index
x(ind) = xt; %save temporary x coordinates
%next temporary x coordinates are the k-1 middle pairwise averages
%calculated by linear interpolation through convolution
xt = conv(xt,[.5,.5]);
xt = xt(2:end-1);
y(ind) = yt; %save temporary y coordinates
yt = yt+1; %update temporary y coordinates
r(ind) = N-k+1; %save row indices
c(ind) = 1:k; % save column indices
end
v = A(sub2ind(size(A),r,c)); %extract values from matrix A
tri = delaunay(x,y); %create triangular mesh
h = trisurf(tri,x,y,z,v,'edgecolor','none','facecolor','interp'); %plot surface
axis vis3d; view(2); %adjust axes projection and proportions
daspect([sqrt(3)*.5,1,1]); %adjust aspect ratio to display equilateral triangle
end %end of function
I have a vector with x and y position.
If n=3 I have array with length 6. Each cell value is a position on space
A= [x1 y1 ,x2 y2 ,x3 y3]
// As example A = [2 3.122 , 1.3 6, 2.1 5.6]
how can I a complete graph of this positions ?
appreciate any help.
gplot(A,Coordinates) plots a graph of the nodes defined in Coordinates according to the n-by-n adjacency matrix A, where n is the number of nodes. Coordinates is an n-by-2 matrix, where n is the number of nodes and each coordinate pair represents one node
For two-dimensional data, Coordinates(i,:) = [x(i) y(i)] denotes node i, and Coordinates(j,:) = [x(j)y(j)] denotes node j. If node i and node j are connected, A(i,j) or A(j,i) is nonzero; otherwise, A(i,j) and A(j,i) are zero.
doc gplot
for more info.
For your example, with the trivial all ones adjacency matrix, you'll get:
A = [2 3.122 , 1.3 6, 2.1 5.6]; % # where A= [x1 y1 ,x2 y2 ,x3 y3]
gplot(ones(3),[A(1:2:end)',A(2:2:end)'],'-*')
You could create an X vector and a Y vector like this:
X = A(:,1);
Y = A(:,2);
and then simply use plot:
plot(X, Y);