MATLAB: Building a matrix starting from another matrix

matrix

I want to build a square matrix. Let's suppose We have this matrix called nodes
1 4.3434 3.4565
2 6.2234 5.1234
3 10.4332 2.3243
4 7.36543 1.1434
where the column 2 and 3 represents position x and y of nodes n
and a matrix called heads where its elements are some elements of nodes matrix
2 6.2234 5.1234
3 10.4332 2.3243
I created this function to build the matrix of the distance of every nodes from the heads
function [distances] = net_dist(nodes,heads)
nnodes = length(nodes(:,1));
distances = zeros(nnodes);
for i = 1 : nnodes
for j = 1 : nnodes
if nodes(i,1) == nodes(j,1) && ismember(nodes(j,1),heads(:,1))
distances(i,j) = sqrt((nodes(i,2) - nodes(j,2))^2 + (nodes(i,3) - nodes(j,3))^2);
elseif (nodes(i,1) == nodes(j,1) || nodes(i,1) ~= nodes(j,1)) && ismember(nodes(j,1),heads(:,1))
distances(i,j) = sqrt((nodes(i,2) - nodes(j,2))^2 + (nodes(i,3) - nodes(j,3))^2);
elseif (nodes(i,1) == nodes(j,1) || nodes(i,1) ~= nodes(j,1)) && ~ismember(nodes(j,1),heads(:,1))
distances(i,j) = 1E9;
end
end
end
return;
This function should return the distance of every nodes from a heads. The positions of nodes that aren't heads are filled with number 1E9. I don't understand why when I execute this function instead to receive sqrt values I receive all 0.
Definitely I would obtain such similar thing
1 2 3 4
1 1E9 d d 1E9
2 1E9 0 d 1E9
3 1E9 d 0 1E9
4 1E9 d 0 1E9

Best Answer

At first I'd simplify the code. E.g. this is useless:
if (nodes(i,1) == nodes(j,1) <OR> nodes(i,1) ~= nodes(j,1))
Of course two number are either equal or not equal, as long as they are not NaNs.
function distances = net_dist(nodes,heads)
nnodes = size(nodes, 1); % Better than "length(nodes(:,1))"
distances = zeros(nnodes);
for i = 1 : nnodes
for j = 1 : nnodes
match = ismember(nodes(j,1),heads(:,1));
if nodes(i,1) == nodes(j,1) && match
distances(i,j) = sqrt((nodes(i,2) - nodes(j,2))^2 + ...
(nodes(i,3) - nodes(j,3))^2);
elseif match
distances(i,j) = sqrt((nodes(i,2) - nodes(j,2))^2 + ...
(nodes(i,3) - nodes(j,3))^2);
else % Now "elseif ~match" *must* be true!
distances(i,j) = 1E9;
end
end
end
Now we see, that the first two IF-branches are performed whenever match is true. So a further simplification:
distances = repmat(1E9, nnodex, nnodes);
matchList = ismember(nodes(:,1), heads(:,1));
for i = 1 : nnodes
for j = 1 : nnodes
if matchList(j)
distances(i,j) = sqrt((nodes(i,2) - nodes(j,2))^2 + ...
(nodes(i,3) - nodes(j,3))^2);
end
end
end
Finally I do not understand also, why you get zeros in the output.
Related Question