2017-01-17 151 views
1

在C How to convert int array to int?中也有類似的問題;然而,我在朱莉婭身上找不到這樣的問題。如何在Julia(Jupyter notebook)中將「1-D int array」轉換爲「int」

我的問題是:

有大約v[1] = x'*y enter image description here

錯誤所以我試圖找到原因,並表明:
enter image description here

然而,x^Ty=2所以如果您直接鍵入2,它是Int64並且沒有錯誤,如下所示:

enter image description here

那麼如何從Array {Int64,1}轉換爲Int 64,1?

+0

'arr_to_int {T <:Number}(x :: Vector {T})= length(x)== 1? Int(x [1]):錯誤(「輸入數組沒有一個元素」) –

回答

1

你必須定義相應的轉換方法:

Base.convert{T}(Float64, x::Array{T, 1}) = float(x[1]) 

或一般

Base.convert{T,K}(::Type{K}, x::Array{T, 1}) = Base.convert(K, x[1]) 

例子:

v = zeros(Complex{Float64}, 3) 
x = [1, 1] 
y = [1, 1] 
v1 = x'*y 
v[1] = v1 
v[2] = 45 
v[3] = 100 
v 

結果:

3-element Array{Complex{Float64},1}: 
    2.0+0.0im 
    45.0+0.0im 
100.0+0.0im 
+0

儘管這是用複選標記標記的,但正確的答案實際上是@Gnimuc的下面。這裏的方法可能會導致各種問題,當傳遞給需要標量的函數時,將第一個元素替換爲第一個元素。 –

5

引擎蓋下的原因是,朱莉婭 - 0.5仍然不take vector transposes seriously,實際上,x'是一個1x2的矩陣:

julia> x' 
1×2 Array{Int64,2}: 
1 1 

顯然,你想獲得的xy點產品,但從技術上來講x'*y不正確的語法,你應該使用dot(x,y)\cdot[tab]

julia> x ⋅ y 
2 

這個問題已經通過引入新型固定在朱莉婭 - 0.6主:

julia> x' 
1×2 RowVector{Int64,Array{Int64,1}}: 
1 1 

julia> x'*y 
2