Convert distance matrix to a table
조회 수: 1 (최근 30일)
이전 댓글 표시
How can I convert the output matrix Z to a table with the following structure?
Object1 Object2 Distance
1 2 0.2954
1 3 1.0670
2 1 0.2954
2 3 0.9448
3 1 1.0670
3 2 0.9448
Code:
rng('default') % For reproducibility
X = rand(3,2);
D = pdist(X)
Z = squareform(D)
댓글 수: 7
Adam Danz
2019년 6월 17일
Here's how to convert a matrix to a table and add column names.
m =[1 2 0.2954
1 3 1.0670
2 1 0.2954
2 3 0.9448
3 1 1.0670
3 2 0.9448];
t = array2table(m,'VariableNames', {'Object1','Object2','Distance'})
Akira Agata
2019년 6월 18일
How about making a graph object?
rng('default') % For reproducibility
X = rand(3,2);
D = pdist(X);
Z = squareform(D);
G = graph(Z);
Then, G.Edges becomes almost what you want to obtain, like:
>> G.Edges
ans =
3×2 table
EndNodes Weight
________ _______
1 2 0.2954
1 3 1.067
2 3 0.94476
답변 (1개)
Akira Agata
2019년 6월 18일
Or, if you want the full list of (from, to, distance) set, how about the following?
rng('default') % For reproducibility
X = rand(3,2);
D = pdist(X);
Z = squareform(D);
[row,col] = find(Z);
d = arrayfun(@(r,c) Z(r,c),row,col);
T = table(row,col,d,'VariableNames',{'Object1','Object2','Distance'});
T = sortrows(T);
The result is:
>> T
ans =
6×3 table
Object1 Object2 Distance
_______ _______ ________
1 2 0.2954
1 3 1.067
2 1 0.2954
2 3 0.94476
3 1 1.067
3 2 0.94476
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!