## Why the same code works for the matrix of size 5 but does not work for the matrix of size 100?

on 12 May 2013

### Matt J (view profile)

Hi,

I have a sparse matrix L of zeros and ones and I want to change the non-zero entries to some fractions. This is my code:

```    beta = 0.5
n = size(L,1); %set n = dim(L)
rsv=ones(1,n)*L; %row sum vector of L
H =L;
for i=1:n
for j=1:n
if H(i,j) == 1
H(i,j)=1/((1-beta)*rsv(i)+ beta*rsv(j));
end
end
end```

I found this code works for the matrix of size 5 but does not work for the matrix of size 100 (all entries stay unchanged).

Do you know why and how to change the code?

Many thanks,

Weijian

Matt J

### Matt J (view profile)

on 12 May 2013

It should also be more efficient to avoid the for-loops as follows

` [i,j,s]=find(L);`
` H=sparse(i,j,1./((1-beta)*rsv(i)+ beta*rsv(j)));`
Weijian

on 12 May 2013

Matt J

### Matt J (view profile)

on 12 May 2013

It is not really clear why this should have made a difference. It is equivalent to your original code, if L is type double. I can only suppose that L was logical and that my other Answer below accounts for the difference.

## Products

No products are associated with this question.

### Matt J (view profile)

on 12 May 2013

If L has a single 1 on all columns then rsv(i)=1 for all i. If that happens then

```1/((1-beta)*rsv(i)+ beta*rsv(j))
```

will equal 1 for all i and j.

Weijian

### Weijian (view profile)

on 12 May 2013

No, this is not the case, most of the columns have more than 1 non-zeros. But never mind, your code solves my problem. Thanks a lot.

on 12 May 2013
Edited by Matt J

### Matt J (view profile)

on 12 May 2013

Another possibility. If L is type logical, then creating H as H=L will make H type logical as well. This means that all assignments

` H(i,j) = something_nonzero`

will convert "something_nonzero" to logical 1.

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi