我很高兴地了解到 Julia 允许以一种非常简洁的方式来形成内积:
julia> x = [1;0]; y = [0;1];
julia> x'y
1-element Array{Int64,1}:
0
dot(x,y)
的替代方案很好,但它可能会带来惊喜:julia> @printf "Inner product = %f\n" x'y
Inner product = ERROR: type: non-boolean (Array{Bool,1}) used in boolean context
julia> @printf "Inner product = %f\n" dot(x,y)
Inner product = 0.000000
所以虽然我想写
x'y
,似乎最好避免它,否则我需要意识到与标量与 1×1 矩阵相关的陷阱。但我是 Julia 的新手,可能我的想法不正确。其他人是否使用这个简洁的替代方案来代替
dot
,如果是这样,什么时候这样做是安全的?
最佳答案
这里有一个概念上的问题。当你做
julia> x = [1;0]; y = [0;1];
julia> x'y
0
这实际上变成了维度分别为 2x1 和 1 的矩阵 * 向量乘积,从而产生了 1x1 矩阵。其他语言(例如 MATLAB)不区分 1x1 矩阵和标量,但 Julia 出于多种原因区分。因此,将其用作“真实”内积函数的替代方法是不安全的
dot
,它被定义为返回一个标量输出。现在,如果您不喜欢
dot
s,可以考虑sum(x.*y)
的 sum(x'y)
.还要记住,列向量和行向量是不同的:事实上,Julia 中没有行向量这样的东西,更多的是有一个 1xN 矩阵。所以你会得到类似的东西julia> x = [ 1 2 3 ]
1x3 Array{Int64,2}:
1 2 3
julia> y = [ 3 2 1]
1x3 Array{Int64,2}:
3 2 1
julia> dot(x,y)
ERROR: `dot` has no method matching dot(::Array{Int64,2}, ::Array{Int64,2})
You might have used a 2d row vector where a 1d column vector was required.
Note the difference between 1d column vector [1,2,3] and 2d row vector [1 2 3].
You can convert to a column vector with the vec() function.
错误信息建议是
dot(vec(x),vec(y)
,但是 sum(x.*y)
在这种情况下也有效,并且更短。julia> sum(x.*y)
10
julia> dot(vec(x),vec(y))
10
关于julia - 形成内积的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966171/