You mean quicker as in faster or as in easier? Using indexing is probably
easiest but not fastest:

julia> M = randn(5,5)
5x5 Array{Float64,2}:
 -1.51134     1.2331    -0.186083   0.412282  -1.13114
 -0.0411132   0.124684   0.377426   0.622427  -0.278162
  0.788182   -0.834092   1.09506    1.45196   -0.620717
  1.45856    -0.889277  -0.768049  -0.95953   -0.340098
  1.69666     0.695566   0.706905   0.63089    0.958474

julia> mean(M[M .> 0])
0.8751552351448673


If you want the fastest, loop through the matrix and keep totals and counts:

julia> function meanpos(a)
           t = zero(eltype(a))
           c = 0
           for x in a
               x > 0 || continue
               t += x
               c += 1
           end
           return t/c
       end
meanpos (generic function with 1 method)

julia> meanpos(M)
0.8751552351448673


This should be fairly efficient for any non-sparse collection.

On Tue, Jul 28, 2015 at 11:50 AM, Jude <[email protected]> wrote:

> Hi!
>
> Probably a quite basic question but was wondering if someone knows a quick
> way to get the average of theh positive elements of a matrix, eg, If I have
> an m*n matrix and want to get the average for each m so have m*1 but only
> want to work with non-zero elements and ignore the zero elements and
> negative elements
>
> I guess I could using indexing and pull out the indexes corresponding to
> the positive elements but just wondering if anyone knew quicker ways!
>
> Thanks!
>

Reply via email to