如何将以下代码(DM)生成的距离矩阵转换为具有特定结构的表?我当时在考虑一个循环,但我不知道如何构造它。
代码:
clc;
clear;
rng('default')
X = rand(4);
DM = squareform(pdist(X))
表结构:
Object1 Object2 Distance
1 2 0.7190
1 3 1.1237
1 4 0.8285
2 1 0.7190
2 3 1.1790
2 4 0.5657
… … …
4 3 1.3360
答案 0 :(得分:3)
我将使用逻辑索引删除对角线,并从中建立表格:
JSON
答案 1 :(得分:2)
这是不使用for循环的解决方案:
meshgrid
构建第一列和第二列的索引。 DM
转换为列向量。 完整的代码示例:
clc;
clear;
rng('default')
X = rand(4);
DM = squareform(pdist(X));
d = length(X);
%Span combinations of rows / columns (indexes)
%C aplies Object1, R aplies Object2
[C, R] = meshgrid(1:d, 1:d);
%Reshape DM, C, R to a column vectors;
Dist = DM(:);
Obj1 = C(:);
Obj2 = R(:);
%Remove items with object distance to itself (i.e (1,1), (2,2), (3,3), (4,4)).
Dist(1:d+1:end) = [];
Obj1(1:d+1:end) = [];
Obj2(1:d+1:end) = [];
%Concatenate columns to create a table:
T = [Obj1, Obj2, Dist];
%Table with named variables (if you really need it).
T_table = table(Obj1, Obj2, Dist);
结果:
T_table =
12×3 table
Obj1 Obj2 Dist
____ ____ _______
1 2 0.719
1 3 1.1237
1 4 0.82577
2 1 0.719
2 3 1.179
2 4 0.56567
3 1 1.1237
3 2 1.179
3 4 1.336
4 1 0.82577
4 2 0.56567
4 3 1.336