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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With