如何在Julia中编写代码以使用1D矩阵?

Iai*_*ing 6 julia

请考虑以下代码

function test(m,B)
    @show typeof(B)
    all_u = rand(m,10)
    one_u = all_u[:,1]
    B*one_u
end
# Works
@show test(3, [1 1 1; 2 2 2])
# Works
@show test(2, [1 1; 2 2])
# Fails
@show test(1, [1; 2])
Run Code Online (Sandbox Code Playgroud)

最后一行失败了

`*` has no method matching *(::Array{Int64,1}, ::Array{Float64,1})
Run Code Online (Sandbox Code Playgroud)

因为B现在是1-D向量(不正常),所以one_u(总是如此,并且不会引起问题).

如何test(m,B)处理m==1不需要实际特殊外壳的情况m==1(即使用if)?我知道,m==1情况我其实写的另一种方法派遣的事实BVector,但似乎非常浪费.

jub*_*0bs 7

引用您的后续评论:

B 有时是矩阵,有时是矢量/ 1D矩阵 - 这就是问题所在.

您可以使用"切片"操作将矢量转换为2D数组[:;:].换句话说,如果B有类型Array{T,1},那么B[:,:]有类型Array{T,2}:

julia> B = [1; 2]
2-element Array{Int64,1}:
 1
 2

julia> typeof(B[:, :])
Array{Int64,2}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果B已经有类型Array{T,2},则[:;:]是无操作:

julia> B = [1 1; 2 2]
2x2 Array{Int64,2}:
 1  1
 2  2

julia> typeof(B[:, :])
Array{Int64,2}

julia> B[:, :] == B
true
Run Code Online (Sandbox Code Playgroud)

因此,为了适应情况的函数定义m==1(即转换B需要时一个二维数组),你可以简单地替换B[:,:]*one_uB*one_u:

julia> function test(m, B)
           @show typeof(B)
           all_u = rand(m, 10)
           one_u = all_u[:, 1]
           B[:, :] * one_u
       end
test (generic function with 1 method)

julia> @show test(3, [1 1 1; 2 2 2])
typeof(B) => Array{Int64,2}
test(3,[1 1 1;2 2 2]) => [1.4490640717303116,2.898128143460623]
2-element Array{Float64,1}:
 1.44906
 2.89813

julia> @show test(2, [1 1; 2 2])
typeof(B) => Array{Int64,2}
test(2,[1 1;2 2]) => [0.9245851832116978,1.8491703664233956]
2-element Array{Float64,1}:
 0.924585
 1.84917 

julia> @show test(1, [1; 2])
typeof(B) => Array{Int64,1}
test(1,[1,2]) => [0.04497125985152639,0.08994251970305278]
2-element Array{Float64,1}:
 0.0449713
 0.0899425
Run Code Online (Sandbox Code Playgroud)