你如何在Julia中的数组中执行条件赋值?

sff*_*ffc 8 octave julia

在Octave,我能做到

octave:1> A = [1 2; 3 4]
A =

   1   2
   3   4

octave:2> A(A>1) -= 1
A =

   1   1
   2   3
Run Code Online (Sandbox Code Playgroud)

但在Julia中,等效语法不起作用.

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
Run Code Online (Sandbox Code Playgroud)

如何在Julia中有条件地为某些数组或矩阵元素赋值?

DSM*_*DSM 16

你的问题不在于作业本身,而是它A > 1本身不起作用.您可以使用elementwise A .> 1:

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
Run Code Online (Sandbox Code Playgroud)

更新:

请注意,在现代Julia(> = 0.7)中,我们需要使用.来表示我们要广播动作(此处,通过标量1000减去)以匹配左侧过滤目标的大小.(在最初询问这个问题的时候,我们需要点,A .> 1但不是.-=.)


DNF*_*DNF 5

在 Julia v1.0 中,您可以使用该replace!函数代替逻辑索引,并获得显着的加速:

julia> B = rand(0:20, 8, 2);

julia> @btime (A[A .> 10] .= 10) setup=(A=copy($B))
  595.784 ns (11 allocations: 4.61 KiB)

julia> @btime replace!(x -> x>10 ? 10 : x, A) setup=(A=copy($B))
  13.530 ns ns (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)

对于较大的矩阵,差异徘徊在 10 倍加速左右。

加速的原因是逻辑索引解决方案依赖于创建一个中间数组,而replace!避免了这种情况。

一种稍微简洁的写法是

replace!(x -> min(x, 10), A)
Run Code Online (Sandbox Code Playgroud)

min但是,使用 似乎没有任何加速。

这是另一个几乎同样快的解决方案:

A .= min.(A, 10)
Run Code Online (Sandbox Code Playgroud)

这也避免了分配。