Using norm Function In MATLAB - matlab

I have a matrix of data which is the coordinates of some points and coordinates of 5 clusters
data = [randi(100,100,1),randi(100,100,1)];
x_Clusters = [20 5 12 88 61];
y_Clusters = [10 50 14 41 10];
Coordinates_Of_Clusters = [x_Clusters',y_Clusters'];
I want to use norm function to determine the distances from the centers of 5 known clusters which are the above coordinates to my data. How could I do that?

The funtion norm(X) is the same as norm(X,2). Matlab uses the 2-norm (Euclidean distance) by default.
Using your code to begin:
% number of data points (trying to harcode less values)
n_points = 100;
data = [randi(n_points,n_points,1),randi(n_points,n_points,1)];
x_Clusters = [20 5 12 88 61];
y_Clusters = [10 50 14 41 10];
Coordinates_Of_Clusters = [x_Clusters',y_Clusters'];
% number of clusters
n_clusters = size(Coordinates_Of_Clusters,1);
% option 1: output is 100-by-10
output_matrix_100x10 = zeros(n_points,2*n_clusters);
% option 2: output is 500-by-2
output_matrix_500x2 = zeros(n_points*n_clusters,2);
Then use for loops for all clusters (n_clusters) and for each point (n_points):
for n = 1:n_clusters
for i = 1:n_points
% option 1
output_matrix_100x10(i,(n-1)*2+1:(n-1)*2+2) = ...
norm(data(i,:)-Coordinates_Of_Clusters(n,:), 2);
% option 2
output_matrix_500x2((n-1)*n_points+i,1:2) = ...
norm(data(i,:)-Coordinates_Of_Clusters(n,:), 2);
end
end

Related

Connecting a set of points to get a non-self-intersecting non-convex polygon

I have an unordered set of 2D points which represents the corners of a building. I need to connect them to get the outline of the building.
The points were obtained by combining different polygons collected by different individuals. My idea is to use these polygons to get the points in order (e.g. taking the region between the biggest and smallest polygons and connect the points such that it comes in this region).
I tried using the minimum distance criteria and also to connect the points based on angles. But unfortunately it doesn't work. One useful thing which I have is the raw data of many polygons in which the point order is correct. So is there any possibility to compare with those polygons to connect these points? As I mentioned above, my professor gave the idea to take the biggest and the smallest polygons and use the area in between as a buffer. All the points will fall in this buffer area. But I am not sure how to implement this.
X = [364.533 372.267 397.067 408.133 382.471 379.533 329.250 257.200 199.412 195.267 184.385 168.643 157.533 174.500 108.533 99.333 150.733 184.800 138.105 179.474 218.278 232.133 267.714 306.929 312.143 357.733 421.333 431.000 371.867 364.533];
Y = [192.027 233.360 228.627 286.693 314.541 292.960 327.450 340.500 348.671 326.693 269.308 330.857 274.493 226.786 239.200 193.467 182.760 101.893 111.000 80.442 74.356 140.360 64.643 56.857 77.786 69.493 133.293 180.427 142.160 192.027];
The expected result is a closed polygon which represents the plan of the building. I have 15 building samples and the code needs to work for all. Some buildings don't preserve the right angle criteria between the corners. I am attaching the data which i had. The points i have is obtained by integrating the polygons. So is there any way to use this polygons(in which the points are in order)actual data before integration
EDIT
So, I could find a solution using my below-mentioned idea.
Remarks: I added one missing point manually. And, I removed the two tiny corners at the bottom. Either, these must be four corners in total, or they can be treated as no corners at all.
I explicitly state that, because my idea incorporates the assumption, that corners typically have a 90 degree angle.
General approach
Find order of points by below-mentioned method.
For all points, determine potential "neighbours" within a limit with respect to the found order.
For each two neighbours, determine the angle between neighbour #1 - current point - neighbour #2. Ideally, this angle should be 90 degree.
For all candidate combinations, find the one with the minimal total distance, i.e. distance(neighbour #1 - current point) + distance(current point - neighbour #2).
I realized that by using a for loop over all points, resulting in drawing all lines two times. Also, a lot of the calculations might by vectorized and moved from the loop. Optimization wasn't my intention right now. ;-)
% Point data of building corners; modified!
X = [285.400 372.267 397.067 408.133 382.471 379.533 199.412 195.267 184.385 168.643 157.533 174.500 108.533 99.333 150.733 184.800 138.105 179.474 218.278 232.133 267.714 306.929 312.143 357.733 421.333 431.000 371.867 364.533];
Y = [130.150 233.360 228.627 286.693 314.541 292.960 348.671 326.693 269.308 330.857 274.493 226.786 239.200 193.467 182.760 101.893 111.000 80.442 74.356 140.360 64.643 56.857 77.786 69.493 133.293 180.427 142.160 192.027];
% Place approximative center of building at (0, 0)
X = X - mean(X);
Y = Y - mean(Y);
C = [mean(X), mean(Y)];
% Sort points by angle with respect to center
[~, idx] = sort(atan2(X, Y));
% Rearrange points with respect to sorted angles
X = X(idx);
Y = Y(idx);
% Number of data points
n = numel(X);
% Calculate direction vectors for X and Y coordinates
dvX = repmat(X.', 1, n);
dvX = dvX - dvX.';
dvY = repmat(Y.', 1, n);
dvY = dvY - dvY.';
% Calculate distances
dst = sqrt(dvX.^2 + dvY.^2);
% Number of "neighbouring" points to be considered with respect to the order
nn = 8;
figure(1);
hold on;
% Center
plot(C(1), C(2), 'kx', 'MarkerSize', 15);
% Plain points
plot(X, Y, '.', 'MarkerSize', 15);
for k = 1:n
% Index
text(X(k) + 0.05, Y(k) + 0.05, num2str(k), 'FontSize', 12);
% Set up neighbourhood
nbh = mod([k-nn/2:k-1 k+1:k+nn/2], n);
nbh(nbh == 0) = n;
% Calculate angles and total distance arrays
ang = Inf(nn);
len = Inf(nn);
for ii = 1:nn
l = nbh(ii);
d1 = [dvX(k, l) dvY(k, l)];
for jj = ii+1:nn
m = nbh(jj);
d2 = [dvX(k, m) dvY(k, m)];
len(ii, jj) = dst(k, l) + dst(k, m);
ang(ii, jj) = abs(pi/2 - acos(dot(d1, d2) / (norm(d1) * norm(d2))));
end
end
% Find candidates with angle difference < 10 degree
cand = find(ang < pi/18);
% For these candidates, find the one with the shortest total distance
[~, I] = min(len(cand));
% Get corresponding indices
[I, J] = ind2sub([nn nn], cand(I));
cand = nbh([I J]);
% Lines
plot([X(k) X(cand(1))], [Y(k) Y(cand(1))], 'b', 'LineWidth', 1);
plot([X(k) X(cand(2))], [Y(k) Y(cand(2))], 'b', 'LineWidth', 1);
end
hold off;
Output image:
An approximative(!) solution is to determine the center of the contour described by the found points, and use atan2 with respect to the center to order the points by angle. See the following code snippet for visualization:
% Points
X = 2 * rand(1, 15) - 1;
Y = 2 * rand(1, 15) - 1;
% Center
C = [0, 0];
% Determine indices
[~, idx] = sort(atan2(X, Y));
figure(1);
hold on;
% Center
plot(C(1), C(2), 'kx', 'MarkerSize', 15);
% Plain points
plot(X, Y, '.', 'MarkerSize', 15);
% Indices and lines
for k = 1:numel(X)
text(X(idx(k)) + 0.05, Y(idx(k)) + 0.05, num2str(k), 'FontSize', 12);
if (k == numel(X))
plot([X(idx(k)) X(idx(1))], [Y(idx(k)) Y(idx(1))], 'b');
else
plot([X(idx(k)) X(idx(k+1))], [Y(idx(k)) Y(idx(k+1))], 'b');
end
end
hold off;
Gives the following output:
Although I'm sure, that a certain amount of the concavities will be correctly handled, I'm afraid, that it'll fail for the given example (especially the upper part). This is, because the image is not a perfect top view, thus angles are kinda "distorted".
Nevertheless, maybe the ordering can boost your minimum distance approach.
Here's a solution which that good for shapes that have outlines made from perpendicular* lines (as the one in your example). The idea is as follows:
We rotate the points to align* them to the XY grid.
We group points into families that have either the same* X or Y coordinates.
For each point we compute two points: the closest horizontally, and the closest vertically, from within the allowed families.
Build a connectivity matrix and transform back.
Just like in HansHirse's answer, I must change the dataset: add a missing corner (pt. 30), remove two non-corners (pts. 7-8), remove the duplicate last point.
* - approximately.
function A = q55511236
%% Initialization:
% Define points:
X = [364.533 372.267 397.067 408.133 382.471 379.533 329.250 257.200 199.412 195.267 184.385 ...
168.643 157.533 174.500 108.533 99.333 150.733 184.800 138.105 179.474 218.278 232.133 ...
267.714 306.929 312.143 357.733 421.333 431.000 371.867];
Y = [192.027 233.360 228.627 286.693 314.541 292.960 327.450 340.500 348.671 326.693 269.308 ...
330.857 274.493 226.786 239.200 193.467 182.760 101.893 111.000 80.442 74.356 140.360 ...
64.643 56.857 77.786 69.493 133.293 180.427 142.160];
%% Preprocessing:
% Centering:
XY = [X;Y] - [mean(X); mean(Y)];
% Rotation:
[U,~,~] = svd(XY,'econ');
rXY = (U.' * XY).';
% Fixing problems w/ some points:
rXY = vertcat(rXY, [-21.8, 66]); % add missing point
rXY(7:8, :) = NaN; % remove non-corners
% figure(); scatter(rXY(:,1),rXY(:,2));
%% Processing:
% Group points according to same-X and same-Y
CLOSE_ENOUGH_DISTANCE = 10; % found using trial and error
[~,~,sameXpts] = uniquetol(rXY(:,1), CLOSE_ENOUGH_DISTANCE, 'DataScale', 1);
[~,~,sameYpts] = uniquetol(rXY(:,2), CLOSE_ENOUGH_DISTANCE, 'DataScale', 1);
% Create masks for distance evaluations:
nP = size(rXY,1);
[maskX,maskY] = deal(zeros(nP));
maskX(sameXpts == sameXpts.') = Inf;
maskY(sameYpts == sameYpts.') = Inf;
% Compute X and Y distances separately (we can do this in the rotated space)
dX = abs(rXY(:,1) - rXY(:,1).') + maskX + 1./maskY;
dY = abs(rXY(:,2) - rXY(:,2).') + maskY + 1./maskX;
[~,nX] = min(dX);
[~,nY] = min(dY);
% Construct connectivity matrix:
A = false(nP);
idxTrue = sub2ind(size(A), repmat(1:nP, [1,2]), [nX(:).', nY(:).']);
A(idxTrue) = true;
%% Plot result:
% Rotated coordinates:
figure(); gplot(A, rXY, '-o'); text(rXY(:,1), rXY(:,2), string(1:nP));
uXY = (U*rXY.').';
% Original coordinates:
figure(); gplot(A, uXY, '-o'); text(uXY(:,1), uXY(:,2), string(1:nP)); axis ij;
Resulting in:
The concept used for the answer is the 'Travelling salesman problem'. A buffer is created around the points and this buffer is included as an extra criterion.
a=[141 188 178 217 229 282 267 307 313 357 372 422 434 365 372 398 411 382 382 233 229 191 185 166 156 183 173 114 97 149 139 139];
b=[109 103 79 76 140 132 64 56 78 72 141 133 180 192 234 228 287 293 315 348 343 348 329 332 270 268 225 240 194 184 108 108];
X=[364.5333 232.1333 397.0667 157.5333 431 421.3333 306.9286 184.3846 357.7333 199.4118 168.6429 179.4737 408.1333 382.4706 150.7333 372.2667 184.8 138.1053 312.1429 108.5333 174.5 195.2667 257.2 99.33333 379.5333 371.8667 329.25 280.7059 267.7143 218.2778];
Y=[192.0267 140.36 228.6267 274.4933 180.4267 133.2933 56.85714 269.3077 69.49333 348.6706 330.8571 80.44211 286.6933 314.5412 182.76 233.36 101.8933 111 77.78571 239.2 226.7857 326.6933 340.5 193.4667 292.96 142.16 327.45 130.5529 64.64286 74.35556];
R = [a' b'];
d = 12;
polyout = polybuffer(R,'lines',d)
figure
%imshow(I2);
hold on
%plot(R(:,1),R(:,2),'r.','MarkerSize',10)
plot(X,Y,'r.', 'MarkerSize', 15)
plot(polyout)
axis equal
hold off
[s,t] = boundary(polyout); %%this is the boundary polygon of the buffer
numPoints = length(clustersCentroids);
x = X; %these are the points to be connected
y = Y;
x([1 2],:)=x([2 1],:);
y([1 2],:)=y([2 1],:);
figure
plot(x, y, 'bo', 'LineWidth', 2, 'MarkerSize', 17);
grid on;
imshow(I2);
xlabel('X', 'FontSize', 10);
ylabel('Y', 'FontSize', 10);
% Make a list of which points have been visited
beenVisited = false(1, numPoints);
% Make an array to store the order in which we visit the points.
visitationOrder = ones(1, numPoints);
% Define a filasafe
maxIterations = numPoints + 1;
iterationCount = 1;
% Define a current index. currentIndex will be 1 to start and then will vary.
currentIndex = 1;
while sum(beenVisited) < numPoints
visitationOrder(iterationCount) = currentIndex;
beenVisited(currentIndex) = true;
% Get the x and y of the current point.
thisX = x(currentIndex);
thisY = y(currentIndex);
%text(thisX + 0.01, thisY, num2str(currentIndex), 'FontSize', 35, 'Color', 'r');
% Compute distances to all other points
distances = sqrt((thisX - x) .^ 2 + (thisY - y) .^ 2);
distances(beenVisited)=inf;
distances(currentIndex) = inf;
% Don't consider visited points by setting their distance to infinity.
[out,idx] = sort(distances);
xx=[x(currentIndex) x(idx(1))]
yy=[y(currentIndex) y(idx(1))]
if isempty(polyxpoly(xx,yy,s,t))
iterationCount = iterationCount + 1;
currentIndex =idx(1);
else
xx=[x(currentIndex) x(idx(2))]
yy=[y(currentIndex) y(idx(2))]
if isempty(polyxpoly(xx,yy,s,t))
iterationCount = iterationCount + 1;
currentIndex =idx(2);
else
xx=[x(currentIndex) x(idx(3))]
yy=[y(currentIndex) y(idx(3))]
if isempty(polyxpoly(xx,yy,s,t))
iterationCount = iterationCount + 1;
currentIndex =idx(3);
else
xx=[x(currentIndex) x(idx(4))]
yy=[y(currentIndex) y(idx(4))]
if isempty(polyxpoly(xx,yy,s,t))
iterationCount = iterationCount + 1;
currentIndex =idx(4);
end
end
end
end
end
% Plot lines in that order.
hold on;
orderedX = [x(visitationOrder); x(1)];
orderedY = [y(visitationOrder) ;y(1)];
plot(orderedX,orderedY, 'm-', 'LineWidth', 2);
title('Result', 'FontSize', 10);

How to efficiently find maximum of selected indices of an array in MATLAB?

Let us say we have the vectors: w, s_on, and s_off. s_on and s_off have the ascending indices of the onset and offset of an event. We need to find the maximum value in during each event. How can we do it without using loop.
for example we may have the following values:
s_on = [5 19 78 101];
s_off = [10 28 97 152];
w = rand(1,200);
The following code does not work:
pv = max(w(s_on(1:end):s_off(1:end)))
Let the data be defined as
s_on = [5 19 78 101];
s_off = [10 28 97 152];
w = rand(1,200);
The maximum for each range of indices can be computed as follows:
[v, t] = max(bsxfun(#ge, 1:numel(w), s_on(:)) & bsxfun(#le, 1:numel(w), s_off(:)), [], 1);
result = accumarray(t(v).', w(v).', [], #max);
A loop would be more readable:
result_loop = NaN(numel(s_on), 1);
for k = 1:numel(s_on)
result_loop(k) = max(w(s_on(k):s_off(k)));
end
Check that both approaches give the same result:
isequal(result, result_loop)

How to create gradient magnitude image in MATLAB

I am given a grayscale image and I would like to create gradient magnitude image from it.
I know there is a function called imgradient, but I have no idea of how to modify the magnitude so that it is computed the following way:
∇f ≈ abs(z7+ 2z8+ z9- z1- 2z2- z3) + abs(z3+ 2z6+ z9- z1- 2z4- z7)
I get that you want to do spatial filtering using sobel mask (as per your equation). So, I suggest you to use following command: BW = edge(I,'Sobel');
Or If you want exact output as per equation given by you then try this:
I = imread('cameraman.tif');
I = padarray(I,[1 1],'symmetric');
sobel_mask_x = [-1 -2 -1; 0 0 0; 1 2 1];
sobel_x = filter2(sobel_mask_x ,I);
sobel_mask_y = sobel_mask_x';
sobel_y = filter2(sobel_mask_y ,I);
sobel_responce = abs(sobel_x)+abs(sobel_y);
figure,imshow(sobel_responce,[]); title('Sobel gradient');
This is faster instead of using for loops.
You have to implement your own gradient function, and apply it to each pixel in the image I:
//example of a 4x5 image I
I = [1 3 2 6 5; 6 1 0 18 21; 13 12 13 14 11; 16 15 28 9 20]
G = I; //set your gradient matrix to be equal to I so that the sides have a value
//get the height and width of image I
[h, w] = size(I);
//loop through each pixel that is not on the side
for x=2:w-1
for y=2:h-1
//for each pixel:
z1 = I(y-1, x-1); //e.g z1 is the pixel on the upper left
z2 = I(y, x-1);
z3 = I(y+1, x-1);
z4 = I(y-1, x);
z6 = I(y+1, x);
z7 = I(y-1, x+1);
z8 = I(y, x+1);
z9 = I(y+1, x+1);
G(y,x) = abs(z7+ 2*z8+ z9- z1- 2*z2- z3) + abs(z3+ 2*z6+ z9- z1- 2*z4- z7);
end
end

How to find minimum distance from one set of points to another set of points in matlab?

I have distributed 100 random points(nodes) in an area by using following code
n=100; xm=100;ym=100;
for i = 1 : 1 :n
S(i).xd = rand(1,1)*xm ;
S(i).yd = rand (1,1)*ym ;
xd(i) = S(i).xd ;
yd(i) = S(i).yd ;
S(i).id = i;
S(i).type = 0;
S(i).g = 0 ;
S(i).E = Eo ;
S(i).type = 0 ;
end
Next I have fixed 10 gateway nodes at the edge of the area using following code
for i=1:1:10
Sg(i).xd= 2+100*rand(1,1);
Sg(i).yd=100;
xd(i)=Sg(i).xd;
yd(i)=Sg(i).yd;
Sg(i).id=i;
plot(Sg(i).xd,Sg(i).yd,'*k')
grid on;
hold on;
end
Now I have formed cluster heads using LEACH protocol from 100 nodes.
I have to find min distance gateway node from a CH. As there are 10 gateway nodes, I have to find which is closer to a CH in the area.
To determine CH I have used following code
for all nodes in the area
temp_rand1=rand;
if(temp_rand1<= (p/(1-p*mod(r,round(1/p)))))
countCHs1=countCHs1+1;
S3(i).type=1;
S3(i).g=round(1/p)-1;
C1(cluster1).xd=S3(i).xd;
C1(cluster1).yd=S3(i).yd;
**distance1=sqrt((S3(i).xd-(gw_node.x) )^2 + (S3(i).yd-(gw_node.y) )^2 );**
C1(cluster1).distance1=distance1;
C1(cluster1).id=i;
X(cluster1)=S3(i).xd;
Y(cluster1)=S3(i).yd;
cluster1=cluster1+1;
end
I know how to determine distance between a CH and one gateway node, But I do not know how to find closet gateway node from a set of gateway nodes.
Thanks in advance
Please reply
Not sure what you are asking. I assume you have set of fixed points in a straight line (marked blue) and set of random points (marked red). You want the Minimal distance between one fixed and one random point.
Try this code:
si = randi([0,100],10,2); %// Random points (red)
sg(:,1) = randi([0,100],10,1); %// fixed points x param (blue)
sg(:,2) = ones(10,1)*50; %// fixed points y param (blue) r const, to make them a st. line
sgc = mat2cell(sg,ones(1,size(sg,1)),size(sg,2)); %// converting to cell array
sic = mat2cell(si,ones(1,size(si,1)),size(si,2)); %// converting to cell array
%// distMat gives n*n matrix of all the dist between each fixed point with every other point.
distMat = cellfun(#(x,y) pdist2(x,y),repmat(sic,1,size(sgc,1)),repmat(sgc',size(sic,1),1));
figure; axis('image');
plot(si(:,1),si(:,2),'r.');
text(si(:,1),si(:,2),[repmat(' ',size(si,1),1), num2str((1:size(si,1))')]);
hold on
plot(sg(:,1),sg(:,2),'b.');
text(sg(:,1),sg(:,2),[repmat(' ',size(sg,1),1), num2str((1:size(sg,1))')]);
hold off
[mdist, index] = min(distMat(:));
[randomP, fixedP] = ind2sub(size(distMat),index)
Plot:
output:
randomP =
2
fixedP =
2
>> mdist
mdist =
6.7082
Not too sure what you are asking for but I think you want to find the two closest points.
This is how you could do it.
%// Generate some points
n = 3; xm = 1:n; ym =1:n;
m = [xm' ym']; %// This is the line
xd = [ 2 8 3];
yd = [ 1 4 3];
d = [xd' yd']; %// These are the random points
drep = repmat(d,n,1); %// This will repeat the matrix d n times
B= ones(n,1);
mrep = kron(m,B); %// This will repeat each value in m n times
distances = bsxfun(#minus,mrep,drep); %// The distance from each point to every other point
C_squared = sum(distances.^2,2)
[min_dist,idx] = min(sum(distances.^2,2)) %// Find the minimum distance
value_in_m = mrep(idx,:)
ans =
3 3
value_in_d = drep(idx,:)
ans =
3 3
Explanation
% Generate some points
n = 3;
xm = 1:n;
ym =1:n;
m = [xm' ym']; %// This is the line. Each row is a point
xd = [ 2 8 3];
yd = [ 1 4 3];
d = [xd' yd']; %// These are the random points
We want to calculate the distance from one point to every
other point so we repeat the points nxn times
Below is just one way of getting repeated elements.
More suggestions are here: https://stackoverflow.com/a/16269185
drep = repmat(d,n,1); %// This will repeat the matrix d n times
B= ones(n,1);
mrep = kron(m,B); %// This will repeat each value in m n times
We are basing this on Pythagoras theorem so (m_x-d_x)^2 + (m_y-d_y)^2 = C^2
distances = bsxfun(#minus,mrep,drep); %// The distance from each point to every other point
C_squared = sum(distances.^2,2)
Find the minimum distance
[min_dist,idx] = min(sum(distances.^2,2));
Find the points with the minimum distance
value_in_m = mrep(idx,:)
ans =
3 3
value_in_d = drep(idx,:)
ans =
3 3

How to draw this tree like lattice structure in Matlab?

The structure that I want to draw should be exactly like the one shown. Thanks!
Here's a little function I whipped up that will take as input a square, upper-triangular matrix and plot the lattice structure as above:
function hFigure = plot_lattice(A)
%# Compute all the coordinates needed for the lines and points:
N = size(A,1);
[xPoints,yPoints] = meshgrid(0:N-1);
yPoints = bsxfun(#plus,-yPoints,0:0.5:(N-0.5)/2);
xLines = [xPoints([1:N+1:N^2-N-1 1:N:N^2-2*N+1]); ...
xPoints([1:N-1 N:-1:2],N).']; %'
yLines = [yPoints([1:N+1:N^2-N-1 1:N:N^2-2*N+1]); ...
yPoints([1:N-1 N:-1:2],N).']; %'
index = find(triu(reshape(1:N^2,N,N)));
xPoints = xPoints(index);
yPoints = yPoints(index);
values = strtrim(cellstr(num2str(A(index))));
%# Create the figure:
hFigure = figure('Color','w');
hAxes = axes('Parent',hFigure,'XLim',[-0.5 N-0.5],...
'YLim',[min(yPoints)-0.5 max(yPoints)+0.5],...
'YColor','w','XTick',0:N-1,'LineWidth',2);
hold on;
plot(hAxes,xLines,yLines,'k','LineWidth',2);
plot(hAxes,xPoints,yPoints,'o','MarkerFaceColor',[0.96 0.96 0.86],...
'MarkerSize',30,'MarkerEdgeColor','k','LineWidth',2);
text(xPoints,yPoints,values,'Parent',hAxes,...
'HorizontalAlignment','center');
hold off;
end
And here's a test with a sample matrix:
>> A = triu(reshape(1:25,5,5))
A =
1 6 11 16 21
0 7 12 17 22
0 0 13 18 23
0 0 0 19 24
0 0 0 0 25
>> plot_lattice(A);
I have modified the code a little so it can print the nodes as well as multiple values in each node.
A is now a three dimension matrix and cant take also empty values (NaN) that are not printed in the tree
Ofc the code is not optimal... maybe one of you can improve it
%# Compute all the coordinates needed for the lines and points:
close all
[N,L] = size(A);
L=L/N;
[xPoints,yPoints] = meshgrid(0:N-1);
yPoints = bsxfun(#plus,-yPoints,0:0.5:(N-0.5)/2);
xLines = [xPoints([1:N+1:N^2-N-1 1:N:N^2-2*N+1]); xPoints([1:N-1 N:-1:2],N).'];
yLines = [yPoints([1:N+1:N^2-N-1 1:N:N^2-2*N+1]); yPoints([1:N-1 N:-1:2],N).'];
index = find(triu(reshape(1:N^2,N,N)));
xPoints = xPoints(index);
yPoints = yPoints(index);
% values = strtrim(cellstr(num2str(A(index))));
for i=1:L
values(:,i) = strtrim(cellstr(num2str(A((i-1)*N*N+index))));
end
values = strrep(values, 'NaN', ' ');
for i=1:N
for j=i:N
if i==1 && j==1
nodes(i,j)=cellstr(strcat('N_','0'));
else
nodes(i,j)=cellstr(strcat('N_','{',repmat('u',1,(j-1)-(i-1)),repmat('d',1,(i-1)),'}'));
end
end
end
nodes = nodes(index);
%# Create the figure:
hFigure = figure('Color','w');
hAxes = axes('Parent',hFigure,'XLim',[-0.5 N-0.5],'YLim',[min(yPoints)-0.5 max(yPoints)+0.5],'YColor','w','XTick',0:N-1,'LineWidth',2);
hold on;
plot(hAxes,xLines,yLines,'k','LineWidth',2);
plot(hAxes,xPoints,yPoints,'o','MarkerFaceColor',[0.96 0.96 0.86],'MarkerSize',60,'MarkerEdgeColor','k','LineWidth',2);
for i=1:L
text(xPoints,yPoints+L*0.05-(i-1)*0.1,values(:,i),'Parent',hAxes,'HorizontalAlignment','center');
end
text(xPoints-0.4,yPoints,nodes,'Parent',hAxes,'HorizontalAlignment','center');
hold off;
I would use matlab to generate a text file for use in Graphviz.