你如何在 Julia 的数组中执行条件赋值? [英] How do you perform conditional assignment in arrays in Julia?
问题描述
在 Octave 中,我可以做到
In Octave, I can do
octave:1> A = [1 2; 3 4]
A =
1 2
3 4
octave:2> A(A>1) -= 1
A =
1 1
2 3
但在 Julia 中,等效语法不起作用.
but in Julia, the equivalent syntax does not work.
julia> A = [1 2; 3 4]
2x2 Array{Int64,2}:
1 2
3 4
julia> A[A>1] -= 1
ERROR: `isless` has no method matching isless(::Int64, ::Array{Int64,2})
in > at operators.jl:33
如何在 Julia 中为某些数组或矩阵元素有条件地赋值?
How do you conditionally assign values to certain array or matrix elements in Julia?
推荐答案
你的问题不在于作业本身,而在于 A >1
本身不起作用.您可以使用元素方式 A .>1
改为:
Your problem isn't with the assignment, per se, it's that A > 1
itself doesn't work. You can use the elementwise A .> 1
instead:
julia> A = [1 2; 3 4];
julia> A .> 1
2×2 BitArray{2}:
false true
true true
julia> A[A .> 1] .-= 1000;
julia> A
2×2 Array{Int64,2}:
1 -998
-997 -996
更新:
请注意,在现代 Julia (>= 0.7) 中,我们需要使用 .
来表示我们要广播动作(这里是减去标量 1000)以匹配左侧的过滤目标.(在最初提出这个问题时,我们需要 A .> 1
中的点,但 .-=
中不需要.)
Note that in modern Julia (>= 0.7), we need to use .
to say that we want to broadcast the action (here, subtracting by the scalar 1000) to match the size of the filtered target on the left. (At the time this question was originally asked, we needed the dot in A .> 1
but not in .-=
.)
这篇关于你如何在 Julia 的数组中执行条件赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!