How to write code for working with 1D matrices in Julia?

Consider the 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 does not work with

 `*` has no method matching *(::Array{Int64,1}, ::Array{Float64,1}) 

because B now a 1-D vector (this is not normal), and therefore one_u (which is always the case and does not cause problems).

How can I write test(m,B) to handle the case m==1 , which does not require a special cover for m==1 (i.e. using if )? I know that for the case m==1 I could write another method to send upon the fact that B is Vector , but that seems terribly wasteful.

+6
source share
1 answer

Quote from your subsequent comment :

B sometimes a matrix, sometimes a vector / 1D matrix - that is the problem.

You can convert a vector to a 2D array using the β€œslicing” [:;:] operation. In other words, if B is of type Array{T,1} , then B[:,:] is of type Array{T,2} :

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

On the other hand, if B already has an Array{T,2} type Array{T,2} , then [:;:] is 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, to adapt your function definition to the case m==1 (i.e., convert B to a 2D array if necessary), you can simply replace B[:,:]*one_u with 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 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 
+6
source

Source: https://habr.com/ru/post/987215/


All Articles