朱莉娅选择数组/矩阵中除一个元素外的所有元素 [英] julia select all but one element in array/matrix
问题描述
我想知道是否可以在julia数组中选择除一个元素(按索引)以外的所有元素.
I would like to know if it is possible to select all but one element (by index) in a julia array.
例如,以R语言为例,为了不选择矩阵中的特定行,可以这样写:
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
然后:
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
或与R中相同:
a[-2, :]
和其他一些选项.茱莉亚的工作原理如下:
and a few other options. What is working in julia is the following:
a[a .>= .5, :]
或
a[[2,3], :]
选择秒和第三行.无论如何,我真的很想知道如何在julia数组中选择一个元素(例如行)中的一个元素.
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.
推荐答案
以下是一种选择:
A = rand(3,3)
B = A[1:end .!= 2,:]
1:end
获取行索引的完整列表(您也可以使用1:size(A,1)
),然后.!=
(请注意.
表示逐元素比较)选择不等于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]
请注意,end
关键字将自动等于您引用的行,列或其他维的最后一个索引值.
Note that the end
keyword automatically will equal the last index value of the row, column, or other dimension you are referencing.
注意:答案已更新,以反映@Matt B在评论中建议的改进(使用end
而不是size()
).
Note: answer updated to reflect improvements (using end
instead of size()
) suggested by @Matt B in comments.
这篇关于朱莉娅选择数组/矩阵中除一个元素外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!