我想用邻接矩阵中的值1替换另一个较小矩阵中给出的权重

时间:2014-03-10 21:47:17

标签: algorithm matlab adjacency-matrix

如何用邻接矩阵中的权重替换邻接矩阵中的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]

2 个答案:

答案 0 :(得分:5)

代码 -

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

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

答案 1 :(得分:4)

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.')).'