I want replace the values of 1 in an adjacency matrix with weights given in another smaller matrix

StackOverflow https://stackoverflow.com/questions/22312034

Question

How can I replace the values of 1 in an adjacency matrix with weights given in another matrix? For example:

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]

The final matrix should look like this: [2 0 0 4; 0 0 6 2; 4 0 5 0; 0 1 3 0]

Was it helpful?

Solution 2

accumarray solution:

>> [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 solution:

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

OTHER TIPS

Code -

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

Inputs 'adjacent_matrix' and 'weight_matrix' stay the same, as suggested by @chappjc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top