bug in linkage function

2 views (last 30 days)
leptogenesis
leptogenesis on 25 Apr 2013
If you load the links variable defined in this mat file (12MB):
and then run the following code in Matlab R2012a:
cluststr=linkage((1:25000)','average',{@(x,y) -links(x,y)+13});
linkage is not mine; it's part of the stats toolbox. You get this error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
file: '/code/MATLAB/R2012b/toolbox/stats/stats/linkage.m'
name: 'fixnonchronologicalZ'
line: 443
file: '/code/MATLAB/R2012b/toolbox/stats/stats/linkage.m'
name: 'rearrange'
line: 422
file: '/code/MATLAB/R2012b/toolbox/stats/stats/linkage.m'
name: 'linkage'
line: 256
Sorry about the weird formatting--running this from within a framework, but I doubt that's the issue.
Anyway, fixnonchronologicalZ seems to be trying to relabel the nodes to make them look tidy. However, the algorithm for doing so seems to assume that each node occurs at least once in columns one and two of Z. This is almost true, but not for the root node. My case seems to require that the algorithm relabel the root node. Here's my fix:
function Z = fixnonchronologicalZ(Z)
% Fixes a binary tree that has branches defined in a non-chronological order
nl = size(Z,1)+1; % number of leaves
nb = size(Z,1); % number of branches
last = nl; % last defined node, we start only with leaves
for i = 1:nb
tn = nl+i; %this node
if any(Z(i,[1,2])>last)
% this node (tn) uses nodes not defined yet, find a node (h) that
% does use nodes already defined so we can interchange them:
h = find(all(Z(i+1:end,[1 2])<=last,2),1)+i;
% change nodes:
Z([i h],:) = Z([h i],:);
nn = nl+h; % new node
% change references to such nodes
-- Z([find(Z(1:2*nb) == nn,1) find(Z(1:2*nb) == tn,1)]) = [tn nn];
++ tonn=find(Z(1:2*nb) == tn,1);
++ Z([find(Z(1:2*nb) == nn,1)]) = [tn];
++ if(~isempty(tonn))
++ Z(tonn) = [nn];
++ end
end
last = tn;
end
I think this fixes the problem, but I'm not entirely sure it's correct since I'm not 100% sure what fixnonchronologicalZ is supposed to be doing. Can somebody check my code and make sure?

Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!