2015-06-21 66 views
5

我很高兴地得知,朱莉娅允许精美简洁的方式来形成内产品:形成内在产品的最佳方式是什么?

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矩阵有关的陷阱。

但我是新来的朱莉娅,可能我没有以正确的方式思考。其他人是否使用dot这个简洁的替代方案?如果是,那么何时可以安全使用?

+2

这不是很清楚你所需要的(或没有),你是什么愿意牺牲,所以我不张贴一个答案: 您可以使用['⋅'运营商( http://julia.readthedocs.org/en/latest/stdlib/linalg/#Base.⋅)而不是'dot'。你也可以[声明](http://julia.readthedocs.org/en/latest/manual/types/#type-declarations)你对变量/返回函数的期望类型:'x = [0; 1]: :Array {Float64,1}' –

回答

4

这里有一个概念问题。当你

julia> x = [1;0]; y = [0;1]; 
julia> x'y 
0 

即实际上与2×1的尺寸和1分别变成矩阵*向量积,导致一个1x1矩阵。其他语言(如MATLAB)不区分1x1矩阵和标量,但Julia出于各种原因。因此使用它作为替代“真实”内部产品功能dot的方法是不安全的,该功能被定义为返回标量输出。

现在,如果你不是dot的粉丝,你可以考虑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 
+0

'dot([1,2,3],[4,5,6])'现在可以在夜间构建中使用。 –

相关问题