Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia select all but one element in array/matrix

I would like to know if it is possible to select all but one element (by index) in a julia array.

For example in R language in order to not select a particular row in a matrix one would write:

a = matrix(1:9, 3, 3)
a
1 4 7
2 5 8
3 6 9

and then:

a[-2, ]
1 4 7
3 6 9

Now I would like to do the same thing in julia. I tried using logical operators, but I cant find a way to (un) select a particular index. Here is what I tried:

a = rand(3,3)
a[.!= 2, :]
ERROR: syntax "!=" is not a unary operator

or as in R:

a[-2, :]

and a few other options. What is working in julia is the following:

a[a .>= .5, :] 

or

a[[2,3], :]

to select the sec and third row. Anyway I would really like to know how to select all but one of a particular element (row for example) in a julia array.

like image 594
Vincent Avatar asked Jun 06 '16 15:06

Vincent


2 Answers

Here is one option:

A = rand(3,3)
B = A[1:end .!= 2,:]

1:end gets a complete list of row indices (you could also use 1:size(A,1)) and then .!= (note the . indicating element-wise comparison) selects the indices not equal to 2.

If you wanted to select columns in this way you would use:

C = A[:, 1:end .!= 2]

Note that the end keyword automatically will equal the last index value of the row, column, or other dimension you are referencing.

Note: answer updated to reflect improvements (using end instead of size()) suggested by @Matt B in comments.

like image 115
Michael Ohlrogge Avatar answered Oct 27 '22 05:10

Michael Ohlrogge


You should use the Not function, which constructs an inverted index:

A = rand(3,3)
A[Not(2), :]
A[:, Not(2)]

You can find the Not function in the InvertedIndices.jl package.

like image 32
fc9.30 Avatar answered Oct 27 '22 06:10

fc9.30