0

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

Nopas
  • 3

2 Answers2

2

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

draks ...
  • 18,449
1

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.

snar
  • 7,388
  • 22
  • 25
  • +1 for taking care of negative entries. You don't mind if I include this in mine as well? – draks ... Dec 15 '13 at 22:42
  • Of course not. Aside: i) is there any way to store x as a temporary variable so that I don't have store it in memory? ii) which of the two (your way or mine) is more computationally efficient? I know next to nothing about MATLAB but want to learn. – snar Dec 15 '13 at 23:22
  • just insert your first into the second B = repmat((sum(abs(A),2) == 0),size((sum(abs(A),2) == 0)')). I've no idea which of these is more efficient. I guess they are quite comparable in runtime... – draks ... Dec 15 '13 at 23:24