我很高兴得知朱莉娅允许以一种非常简洁的方式来形成内在产品:
julia> x = [1;0]; y = [0;1];
julia> x'y
1-element Array{Int64,1}:
0
Run Code Online (Sandbox Code Playgroud)
这个替代方案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
Run Code Online (Sandbox Code Playgroud)
因此,虽然我想写x'y,但似乎最好避免它,因为否则我需要意识到与标量和1对1矩阵相关的陷阱.
但我是朱莉娅的新手,可能我并没有以正确的方式思考.其他人是否使用这种简洁的替代方案dot,如果是这样,何时可以安全使用?
这里有一个概念问题.当你这样做
julia> x = [1;0]; y = [0;1];
julia> x'y
0
Run Code Online (Sandbox Code Playgroud)
这实际上变成了矩阵*向量积,其尺寸分别为2x1和1,得到1x1矩阵.其他语言,如MATLAB,不区分1x1矩阵和标量,但Julia的原因有多种.因此,使用它作为"真正的"内积函数的替代是不安全的dot,其被定义为返回标量输出.
现在,如果你不是一个球迷dotS,可以考虑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.
Run Code Online (Sandbox Code Playgroud)
错误消息建议是dot(vec(x),vec(y),但sum(x.*y)在这种情况下也适用,并且更短.
julia> sum(x.*y)
10
julia> dot(vec(x),vec(y))
10
Run Code Online (Sandbox Code Playgroud)