How to write this simple matlab script to create a matrix from another matrix.

443 Views Asked by At

I have a matrix $A= \pmatrix{ 0 & 1/3 & 1/3 & 1/3 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 1/2 & 1/2 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 \\ }$ and I wish to add another matrix B which has the row entries $d_i= 1$ (vector of all 1's) if the ith row of A is $0$ and $d_i=0$ otherwise.

I'm unsure how to write a script for this. I can do it manually row by row but wish to learn a quicker more efficient way which I'll be able to build upon.

Edit: I forgot to include I wish the row of 1's on B to be 1/n where n is the dimension so here n=6. Thanks

2

There are 2 best solutions below

1
On BEST ANSWER

kron(sum(abs(A)')'==0,ones(1,length(A)))/length(A)

3
On

I think draks' method is better. I did

x = sum(abs(A),2) == 0
B = repmat(x,size(x'))

If you're not worried about negative entries, you can replace abs(A) by A.