Adding just 1 to a string?

I have a very large matrix (about 4000000x2) and it has 1s sprinkled with all the matrix. What I want to do is that I just want to add all 1s on one line.

For example, if I have a matrix like this:

A = [0 0 4 1 0 0 1
     1 0 5 0 7 0 1 
     5 6 0 8 1 0 6 
     0 9 5 1 0 0 0]

      

Is there a way to sum all 1 rows? For example, here it would be:

sum = [2
       2
       1
       1] 

      

I know that if you want to add the entire line, you can use sum(A,2)

. But is there a way in Matlab to add all specific numbers? I am new to Matlab and I would really appreciate any help, thanks!

+3


source to share


1 answer


Generating an array with 1 everywhere A

has 1 and 0 everywhere:

>> A == 1
ans =
     0     0     0     1     0     0     1
     1     0     0     0     0     0     1
     0     0     0     0     1     0     0
     0     0     0     1     0     0     0

      



Then you can simply use sum

:

sum(A == 1, 2)

      

+7


source







All Articles