Assignment to Matrix

It seems that assignment to a matrix (as opposed to a tuple) is not supported, right ?

function foo()
    return [[[1,2,3],"abc",'e'] [1, 2, 3]]
end

[a b; c d; e f] = foo() #error

Is there any simple workaround (other than the obvious one to stick with tuples) ?

Uhm… I think you either want a new matrix or to replace the elements of a previously allocated matrix:

julia> function foo()
           return [[[1,2,3],"abc",'e'] [1, 2, 3]]
       end
foo (generic function with 1 method)

julia> a = foo()
3Ă—2 Array{Any,2}:
 [1, 2, 3]  1
 "abc"      2
 'e'        3

julia> a = Matrix{Any}(undef,3,2) 
3Ă—2 Array{Any,2}:
 #undef  #undef
 #undef  #undef
 #undef  #undef

julia> a .= foo()
3Ă—2 Array{Any,2}:
 [1, 2, 3]  1
 "abc"      2
 'e'        3


Or do you want six variables with names a, … f associated to the elements of the matrix that comes out from foo()?

1 Like

Yeah it’s entirely non-obvious what the goal is. But if you mean some kind of “array destructuring” similar to how tuple destructuring works, then this should totally be possible but I haven’t seen an implementation of it yet. What already works is:

julia> (a,b,c,d) = [1 2 ; 3 4]
2Ă—2 Array{Int64,2}:
 1  2
 3  4

julia> a
1

julia> b
3

julia> c
2

julia> d
4

So all it’d take is some metaprogramming magic for a macro to flatten the left-hand side to a tuple in the same way that the right-hand side is flattened. (and maybe some shape checking)
Too bad I’m bad at this, but you could try it yourself: Metaprogramming · The Julia Language

I was meaning the second one (having the 6 variables associated to the elements of the matrix).

The idea was for a function like:

[m1Part1 m1Part2 m1Part3; m2Part1 m2Part3 m2Part3] = partition([matrix1,matrix2],[0.7,0.2,0.1])

where then I was interested only in the individual matrices (like xtrain, xvalidation, xtest…) rathen than in the whole matrix itself coming out from partition.

But I can stick with tuples, just having it in a matrix form would have been more elegant…