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);
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
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.
Best Answer