Julia-控制台的行为与include(“ myfile.jl”)不同

时间:2018-11-10 14:35:07

标签: julia

我想执行以下代码,当我在Windows 10的Julia控制台中键入每一行时,效果很好,但是由于类型"server": { "builder": "@angular-devkit/build-angular:server", "options": { "outputPath": "dist/server", "main": "src/main.server.ts", "tsConfig": "src/tsconfig.server.json", "sourceMap": false }, ... 不匹配而引发错误(我的后续代码期望{{ 1}})。

这是代码:

public Bitmap getRandomTwo()
        {
            Bitmap alone = new Bitmap(1, 2);
            alone.SetPixel(0, 0, Color.White);
            alone.SetPixel(0, 1,Color.Black);
            return alone;
        }

存在TypeError,因为LinearAlgebra.Adjoint{Float64,Array{Float64,2}}的类型似乎是Array{Float64,2}而不是x = [0.2, 0.1, 0.2] y = [-0.5 0.0 0.5] fx = x * y fy = fx' return fx::Array{Float64,2}, fy::Array{Float64,2}

如何进行转置并获取“普通” Array {Float64,2}对象?

为什么当我在Julia控制台中键入每一行时却能正常工作,而当我通过include(“ myfile.jl”)运行文件时却不能这样做?

2 个答案:

答案 0 :(得分:3)

使用collect获取实际数据的副本,而不是原始数据的转换视图(请注意,此规则适用于许多其他类似情况):

julia> x = [0.2, 0.1, 0.2];                         
julia> y = [-0.5 0.0 0.5];

julia> fx = x * y                                     
3×3 Array{Float64,2}:                                 
 -0.1   0.0  0.1                                      
 -0.05  0.0  0.05                                     
 -0.1   0.0  0.1                                      

julia> fy = fx'                                       
3×3 LinearAlgebra.Adjoint{Float64,Array{Float64,2}}:  
 -0.1  -0.05  -0.1                                    
  0.0   0.0    0.0                                    
  0.1   0.05   0.1                                    

julia> fy = collect(fx')                              
3×3 Array{Float64,2}:                                 
 -0.1  -0.05  -0.1                                    
  0.0   0.0    0.0                                    
  0.1   0.05   0.1            

答案 1 :(得分:2)

要获得正常的Matrix{Float64},请使用:

fy = permutedims(fx)

fy = Matrix(fx')

这两个通常不是100%等价的,因为fx'是递归的伴随运算(共轭转置),而permutedims是非递归的转置,但是在您的情况下,它们将给出相同的结果结果。

递归伴随到底是什么意思?

  • 递归:共轭转置将以递归方式应用于数组的所有条目(在您的情况下,您具有数字数组,并且数字的转置是相同的数字,因此这不会改变任何内容);
  • 伴随:如果您有复数,则该操作将返回其复数共轭(在您的情况下,您有实数,因此这不会更改任何内容);

这是一个在两个方面都很重要的例子:

julia> x = [[im, -im], [1-im 1+im]]
2-element Array{Array{Complex{Int64},N} where N,1}:
 [0+1im, 0-1im]
 [1-1im 1+1im]

julia> permutedims(x)
1×2 Array{Array{Complex{Int64},N} where N,2}:
 [0+1im, 0-1im]  [1-1im 1+1im]

julia> Matrix(x')
1×2 Array{AbstractArray{Complex{Int64},N} where N,2}:
 [0-1im 0+1im]  [1+1im; 1-1im]

但是,除非确实需要,否则如果确实需要获取数据的共轭转置,则不必这样做。将类型断言更改为

return fx::Array{Float64,2}, fy::AbstractArray{Float64,2}

return fx::Matrix{Float64}, fy::AbstractMatrix{Float64}

共轭转置旨在避免不必要的数据分配,并且在大多数情况下,这将对您更有效(尤其是对于大型矩阵)。

最后一行:

return fx::Array{Float64,2}, fy::Array{Float64,2}

还在Julia命令行中引发错误(不仅是从脚本运行时)。

相关问题