在Julia中,点运算符.
被用于表示按元素的操作,这样就可以在不使用循环的情况下轻松地对数组进行操作。
- a=[1,2,3]
- a
- #3-element Vector{Int64}:
- # 1
- # 2
- # 3
-
- a+2
- #=
- '''
- MethodError: no method matching +(::Vector{Int64}, ::Int64)
- For element-wise addition, use broadcasting with dot syntax: array .+ scalar
- Closest candidates are:
- +(::Any, ::Any, ::Any, ::Any...)
- @ Base operators.jl:578
- +(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8}
- @ Base int.jl:87
- +(::T, ::Integer) where T<:AbstractChar
- @ Base char.jl:237
- ...
- Stacktrace:
- [1] top-level scope
- @ In[11]:1
- '''
- =#
直接加会报错,这时候需要使用.
,让Julia广播标量B
到A
的大小
- a.+2
- #=
- '''
- 3-element Vector{Int64}:
- 3
- 4
- 5
- '''=#
使用.
,Julia会将B
广播到A
的大小,然后进行按元素的加法
- a=[1 2 3; 4 5 6]
- a
- #=
- '''
- 2×3 Matrix{Int64}:
- 1 2 3
- 4 5 6
- '''
- =#
-
- b=[1;2]
- b
- #=
- '''
- 2-element Vector{Int64}:
- 1
- 2
- '''=#
-
- a.+b
- #=
- '''
- 2×3 Matrix{Int64}:
- 2 3 4
- 6 7 8
- '''
- =#
- f(x) = x^2 + 2*x + 1
-
- A = [1, 2, 3]
- G = f.(A)
- '''
- 3-element Vector{Int64}:
- 4
- 9
- 16
- '''
- 1.+a
- '''
- syntax: invalid syntax "1.+"; add space(s) to clarify
- Stacktrace:
- [1] top-level scope
- @ In[27]:1
- '''
这也很好理解:1.+x 到底是表示 1. + x 还是 1 .+ x?