Convert distance matrix to a table

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 comentarios

Your data do not produce the example.
Z =
0 0.2954 1.067
0.2954 0 0.94476
1.067 0.94476 0
dan kin
dan kin el 6 de Jun. de 2019
I used rand.Maybe because of this?
Adam Danz
Adam Danz el 6 de Jun. de 2019
I set the RNG seed which should produce the same results. If you look carefully, you'll see that except for the 0s, the numbers in my Z are also in your example.
dan kin
dan kin el 6 de Jun. de 2019
The output I showed in my question is table I wish to generate
Adam Danz
Adam Danz el 6 de Jun. de 2019
I don't know how you produced the matrix but to convert it to a table, see my answer below. If you need help producing the matrix, you'll have to provide more info about it.
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'})
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

Iniciar sesión para comentar.

Respuestas (1)

Akira Agata
Akira Agata el 18 de Jun. de 2019
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

Categorías

Productos

Versión

R2019a

Preguntada:

el 6 de Jun. de 2019

Respondida:

el 18 de Jun. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by