2015-06-21 62 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])'現在可以在夜間構建中使用。 –

相關問題