Вот решение без использования цикла for:
- Построить индексы первого и второго столбцов, используя
meshgrid
.
- Преобразование индексов и
DM
в векторы столбцов.
- Удалить каждый 4-й элемент (расстояние до объекта).
Полный пример кода:
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