我想把邻接矩阵中的1替换成另一个较小矩阵中的权重



如何将邻接矩阵中的1值替换为另一个矩阵中给定的权重?例如:

adjacent_matrix = [1 0 0 1; 0 0 1 1; 1 0 1 0; 0 1 1 0 ]
weight_matrix = [ 2 4 6 2; 4 5 1 3]

最终的矩阵应该是这样的:[2 0 0 4; 0 0 6 2; 4 0 5 0; 0 1 3 0]

Code -

out = adjacent_matrix';
out(out==1) = reshape(weight_matrix',1,numel(weight_matrix))';
out = out';

输入'adjacent_matrix'和'weight_matrix'保持不变,如@chappjc所建议的。

accumarray解:

>> [ii,jj] = find(adjacent_matrix.');
>> out = accumarray([ii jj],reshape(weight_matrix.',[],1)).'
out =
     2     0     0     4
     0     0     6     2
     4     0     5     0
     0     1     3     0

sparse溶液:

[ii,jj] = find(adjacent_matrix.');
out = full(sparse(ii,jj,weight_matrix.')).'

最新更新