How can I write code to work with 1D matrices in Julia? -
consider following code
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])
the last line fails with
`*` has no method matching *(::array{int64,1}, ::array{float64,1})
because b
1-d vector (which not ok), , one_u
(which case, , doesn't cause issues).
how can write test(m,b)
handle m==1
case doesn't require special casing m==1
(i.e. using if
)? know m==1
case write method dispatch on fact b
vector
seems terribly wasteful.
quoting your follow-up comment:
b
matrix, vector/1d matrix - that's problem.
you can convert vector 2d array "slicing" operation [:;:]
. in other words, if b
has type array{t,1}
, b[:,:]
has type array{t,2}
:
julia> b = [1; 2] 2-element array{int64,1}: 1 2 julia> typeof(b[:, :]) array{int64,2}
on other hand, if b
has type array{t,2}
, [:;:]
no-op:
julia> b = [1 1; 2 2] 2x2 array{int64,2}: 1 1 2 2 julia> typeof(b[:, :]) array{int64,2} julia> b[:, :] == b true
therefore, in order accommodate function definition case m==1
(i.e. convert b
2d array when needed), can substitute b[:,:]*one_u
b*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 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
Comments
Post a Comment