Reputation: 1322
Suppose I have an Array of matrices, named A.
Array{Array{Float64,2},1},
If I create another matrix, eye(3) for instance, I can append it to the end with push!(A,eye(3)). This, however, modifies A which I do not want. Ideally what I'm looking for is some syntactic sugar like
B=[A;eye(3)]
where B is of type Array{Array{Float64,2},1}, B[end] is eye(3) and length(B) is length(A)+1.
This syntax B=[A;eye(3)] does not work however. Can someone point me in the right direction.
Upvotes: 2
Views: 568
Reputation: 1750
In both v0.4.5 and v0.5 (master), you can simply do the following:
B = push!(copy(A), eye(3))
Upvotes: 6
Reputation: 18560
I think the answer may depend on which version of Julia you are using.
For v0.4.x, as you have noted, square bracket concatenation is failing. This is because the syntax is literally saying: create a new vector, where the first element is A
, and the second element is eye(3)
. Since A
is of type Array{Array{Float64,2},1}
but eye(3)
is of type Array{Float64, 2}
, the operation fails.
In order to concatenate correctly, you need to ensure you are concatenating objects of the same type. The easiest way to do this is to convert your eye(3)
into type Array{Array{Float64,2},1}
and then perform the concatenation. There are several ways to do this. Personally I usually just use a comprehension, e.g.
B = [A ; Matrix{Float64}[ eye(3) for n = 1:1 ]]
Note that B
still refers to A
, so, for example, B[1][1,1] = 0.0
will also adjust the contents of the original A
. If you want B
to be a truly independent copy, then you'll need:
B = [deepcopy(A) ; Matrix{Float64}[ eye(3) for n = 1:1 ]]
I think there is a neater way to accomplish all of this on the master branch (v0.5), but I'm still on v0.4.x myself. I think that in v0.5 you could just do [eye(3)]
to get a Array{Array{Float64,2},1}
.
Upvotes: 2