Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a specific subarray in Julia

Tags:

julia

from the array

[3,1,7,2;
4,3,2,7;
3,4,1,2]

I would like to extract the subarray corresponding to the rows having last entree equal to 2.

I am a Matlab user trying to start using Julia. I looked up for an hint in the docs but failed to find a working answer.

Thank you very much in advance,

Stephane

like image 732
SGC Avatar asked Sep 10 '26 10:09

SGC


1 Answers

Does this work for you?

julia> x = [3 1 7 2
            4 3 2 7
            3 4 1 2]
3x4 Array{Int64,2}:
 3  1  7  2
 4  3  2  7
 3  4  1  2

julia> x[x[:, end] .== 2, :]
2x4 Array{Int64,2}:
 3  1  7  2
 3  4  1  2

Let's break it down.

x[:, end] is the last column.

x[:, end] .== 2 gives is a Vector{Bool} (1d array of true and false), where we have true if that row ends in a 2 and false otherwise.

Then putting it all together we have x[x[:, end] .== 2, :], which takes this vector of true and false to specify which rows and the ,: says take all columns in each of those rows.

like image 134
spencerlyon2 Avatar answered Sep 13 '26 22:09

spencerlyon2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!