Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put even numbers from matrix in separate vector in Julia?

I am solving some matrix problems in Julia and i need to put numbers that can be divided by 2 (or any other number) from matrix in separate vector. Generally, when I need to separate numbers from matrix that can be divided with 2 or 3 or 4...etc i can't index them properly. Basically, I need Julia equivalent for Matlab command:

vector=matrix(rem(matrix,2)==0)

.

I tried few things mentioned below:

vector=matrix[matrix.%2==0];

vector=(matrix.%2==0);

I expect output to be vector of numbers that can be divided with certain number but in first case I get errors and in second I only get "true" or "false".

This is my first post, so sorry if I made any mistakes or broke any rules. Thanks in advance!

like image 201
Vasilije Bursac Avatar asked Mar 03 '23 06:03

Vasilije Bursac


1 Answers

First of all, welcome to stackoverflow!

One way to get what you want, that you almost got right, is the following:

julia> M = rand(1:10, 3,3)
3×3 Array{Int64,2}:
 3  10  7
 6   7  8
 2  10  6

julia> v = M[M .% 2 .== 0]
6-element Array{Int64,1}:
  6
  2
 10
 10
  8
  6

Note the extra dot in .== which applies the equality comparison elementwise.

A faster version would be to use findall:

julia> M[findall(x->x%2==0, M)]
6-element Array{Int64,1}:
  6
  2
 10
 10
  8
  6

Here, x->x%2==0 is a anonymous function representing the find criterium. In the special case x%2==0 this can simply be replaced by iseven:

julia> M[findall(iseven, M)]
6-element Array{Int64,1}:
  6
  2
 10
 10
  8
  6

You can also utilize array-comprehensions to get what you want as well, which should be even faster:

julia> [x for x in M if iseven(x)]
6-element Array{Int64,1}:
  6
  2
 10
 10
  8
  6

Finally, perhaps the most idomatic option, is to use filter:

julia> filter(iseven, M)  
6-element Array{Int64,1}: 
  6                       
  2                       
 10                       
 10                       
  8                       
  6                       
like image 191
carstenbauer Avatar answered May 12 '23 17:05

carstenbauer