How to select odd numbers from a matrix?

Viewed 413

How do you select odd numbers from a matrix larger than 29?

2 Answers

You can use filter:

filter(x->isodd(x)&&x>29, M)

Here, x->isodd(x)&&x>29 is an anonymous function, specifying your filter criterium, and M is your matrix.

Example:

julia> M = rand(1:50, 3,3)
3×3 Array{Int64,2}:
 20  42  35
 23   6  31
 28   4   4

julia> filter(x->isodd(x)&&x>29, M)
2-element Array{Int64,1}:
 35
 31

Alternatively, you can use array comprehensions:

julia> [x for x in M if isodd(x) && x>29]
2-element Array{Int64,1}:                
 35                                      
 31                                      

You can also use this:

using Statistics; 
A = round.(rand(5,5)*10) 
odd = A[(rem.(A,2).>0) .& (A.>29)]                          
Related