简体   繁体   English

使用 Julia 的点符号和就地操作

[英]Using Julia's dot notation and in place operation

How do I use both Julia's dot notation to do elementwise operations AND ensure that the result is saved in an already existing array?我如何使用 Julia 的点符号来进行元素操作并确保结果保存在一个已经存在的数组中?

function myfun(x, y)
    return x + y
end

a = myfun(1, 2)  # Results in a == 3

a = myfun.([1 2], [3; 4])  # Results in a == [4 5; 5 6]

function myfun!(x, y, out)
    out .= x + y
end

a = zeros(2, 2)
myfun!.([1 2], [3; 4], a)  # Results in a DimensionMismatch error

Also, does @. a = myfun([1 2], [3; 4])另外, @. a = myfun([1 2], [3; 4]) @. a = myfun([1 2], [3; 4]) write the result to a in the same way as I am trying to achieve with myfun!() ? @. a = myfun([1 2], [3; 4])将结果写入a的方式与我尝试使用myfun!()实现的方式相同? That is, does that line write the result directly to a without saving storing the result anywhere else first?也就是说,该行是否将结果直接写入a而不首先将结果存储在其他任何地方?

Your code should be:你的代码应该是:

julia> function myfun!(x, y, out)
           out .= x .+ y
       end
myfun! (generic function with 1 method)

julia> myfun!([1 2], [3; 4], a)
2×2 Matrix{Float64}:
 4.0  5.0
 5.0  6.0

julia> a
2×2 Matrix{Float64}:
 4.0  5.0
 5.0  6.0

As for @. a = myfun([1 2], [3; 4])至于@. a = myfun([1 2], [3; 4]) @. a = myfun([1 2], [3; 4]) - the answer is yes, it does not create temporary arrays and operates in-place. @. a = myfun([1 2], [3; 4]) - 答案是肯定的,它不会创建临时 arrays 并就地运行。

This isn't commonly required, and there are usually better ways to achieve this, but it's possible to broadcast on an output argument by using Ref erence values that point inside the output array.这通常不是必需的,通常有更好的方法来实现这一点,但可以通过使用指向Ref数组内部的引用值来广播 output 参数。

julia> a = zeros(2, 2)
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> function myfun!(out, x, y)
          out[] = x + y
       end
myfun! (generic function with 1 method)

julia> myfun!.((Ref(a, i) for i in LinearIndices(a)), [1 2], [3; 4])
2×2 Matrix{Int64}:
 4  5
 5  6

julia> a
2×2 Matrix{Float64}:
 4.0  5.0
 5.0  6.0

Edit : Changed out to be the first parameter as per the Style guide - thanks to @phipsgabler for the reminder.编辑:根据样式指南更改为第一个参数 - 感谢@phipsgabler out提醒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM