How to count the number of occurances in an array for each column

#1

Hello,

Suppose I have a 3x3 array of values that include 0. I would like to know the number of occurrences/times per column that contains a value greater than 0 (in other words count the number of times a column does not include a zero).

What I think I need to do is:

a = [1 2 0; 2 0 0;3 1 1]
count(i->(i>0), a[,:])

But this gives me ERROR: syntax: unexpected ","

It is important for me to know the number of occurrences per column as this number is then used in a formula further on.

Any advice is appreciated.

#2

Do you want

  1. The number of columns with no zeros
  2. The number of non-zeros per column
  3. The number of values greater than zero per column
    ?

You seem to ask for all three at various points in your post.

Edit: sorry, you only ask for 1 and 3.

#3

I don’t think a[,:] is a valid syntax. May be something like this?

julia> a = [1 2 0; 2 0 0;3 1 1];

julia> sum(a.>zero(eltype(a)),dims=1)
1×3 Array{Int64,2}:
 3  2  1
#4
sum(x->x>0, a, dims=1) 

Btw, in comparisons you don’t need all the zero/eltype stuff. Just use >0

1 Like
#5

Sorry, I mean 3, the number of values greater than zero per column.

#6

Thank you. I was trying to tell Julia I was interested only in each column in a.

#7

To build further, I would like to be able to place the number of values greater than zero per column into the following formula:

b .= 1/(sum(x->x>0, a, dims=1))

But this generates
**syntax: incomplete: premature end of input**

#8

Your error message seems to be related to something else, maybe due to an incomplete Julia expression.

However your code would still give an error because the division would not work.

julia> 1/(sum(x->x>0, a, dims=1))
ERROR: MethodError: no method matching /(::Int64, ::Array{Int64,2})

I guess you want to do the division element by element:

b = 1 ./(sum(x->x>0, a, dims=1))
1 Like
#9

Thank you! I was missing a bracket. I am new to Julia (and programing) and get confused about where to place . to broadcast. I’ve read the documentation but its just something I will have to practice.