我想从下面的代码中消除for循环并对其进行矢量化,但它是一个二维操作。你能帮我吗?
for i=1:10
savingsFull(i,:) = distances(i,9)+distances(9,knnIdx(i,:))-distances(i,knnIdx(i,:));
end
这里,“距离”是10x10对称矩阵,“knnIdx”是10x2矩阵,如下所示:
1 10
2 10
3 8
4 8
5 4
6 5
7 2
8 4
9 8
10 1
“savingsFull”也是一个10x2矩阵。
答案 0 :(得分:1)
以下代码应该有所帮助:
savingsFull = distances(:, [9 9]) + [distances(9, knnIdx(:, 1)).', distances(9, knnIdx(:, 2)).'] - [diag(distances(:, knnIdx(:, 1))), diag(distances(:, knnIdx(:, 2)))]
如果knnIdx的第一列是从1到10的结果数字,那么你可以简化为
savingsFull = distances(:, [9 9]) + [distances(9, knnIdx(:, 1)).', distances(9, knnIdx(:, 2)).'] - [diag(distances), diag(distances(:, knnIdx(:, 2)))]