如何在Julia中对数组执行条件赋值? [英] How do you perform conditional assignment in arrays in Julia?

查看:414
本文介绍了如何在Julia中对数组执行条件赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在八度音阶中,我可以做

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本身不起作用的原因.您可以改为使用elementwise 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆