如何在距离矩阵中传递成对距离值

时间:2013-05-31 20:49:07

标签: matlab matrix matlab-guide

我对Matlab很新,现在我想用matlab做一些聚类工作。 如果我有3列值

id1 id2 distvalue1

id1 id3 distvalue2 ....

id2 id4 distvalue i .....

总共5000个ID,但有些id对缺少距离值 在python中我可以创建循环以将这些距离值导入矩阵形式。我怎么能在matlab中做到这一点? 并让matlab知道id1,... idx是标识,第三列是值

谢谢!

1 个答案:

答案 0 :(得分:0)

根据评论,您知道如何将数据转换为N x 3矩阵的形式,称为X,其中X(:,1)是第一个索引,X(:,2)是第二个索引,并且X(:,3)是相应的距离。

假设索引(id1 ... idx)是任意数字标签。

那么我们可以做到以下几点:

% First, build a list of all the unique indices    
indx = unique([X(:,1); X(:,2)]);
Nindx = length(indx);

% Second, initialize an empty connection matrix, C
C = zeros(Nindx, Nindx);  %or you could use NaN(Nindx, Nindx)

% Third, loop over the rows of X, and map them to points in the matrix C
for n = 1:size(X,1)
     row = find(X(n,1) == indx);
     col = find(X(n,2) == indx);
     C(row,col) = X(n,3);
end

这不是最有效的方法(将矢量化方式将X的索引重新映射到范围[1 ... Nindx]),但它应该适用于5000个ID。

如果最终处理大量的唯一索引,其中只有极少数索引对已分配距离值,那么您可能需要查看使用稀疏矩阵 - 尝试help sparse - - 而不是预先分配一个大的零矩阵。

相关问题