'Julia - How do I add a matrix to a list of matrices
I'm new to Julia, and I am currently working on a model where I need to add a matrix to list of matrices. I am trying to accomplish this with:
push!(BranchDomainNew, BranchDomain[k])
Where BranchDomainNew is a 1x7 matrix (3D) made up of matrices. I am trying to append BranchDomain[k] (another matrix of the same dimensions) to this list. Ultimately, my goal is to have BranchDomainNew be 8 matrices long, with the last index containing BranchDomain[k].
Here's the error I keep getting:
MethodError: no method matching push!(::Matrix{Any}, ::Matrix{Bool})
I also tried using append!(), which unfortunately also did not work - I got the same error (except append! instead of push!). I'd love to know why these methods don't work for this, and how I can accomplish this goal. Also, I am working with version v"1.7.2". Thanks
Solution 1:[1]
You cannot push! or append! elements to a matrix, because matrices are 2-dimensional entities, and adding single elements could ruin its shape, and is therefore not allowed. You can instead concatenate rows or columns using hcat or vcat.
But it looks like what you really should use is a Vector, not a 1xN Matrix.
So make sure that BranchDomainNew is a Vector of matrices, instead of a Matrix of matrices. Then you can push! and append! all you like.
You did not show how you made your matrix, but it is possible that you did something like this:
BranchDomainNew = [mat1 mat2 mat3] # create 1x3 Matrix
when you should have done
BranchDomainNew = [mat1, mat2, mat3] # create length 3 Vector
It is a common mistake for many new Julia users to use 1xN or Nx1 matrices, when they should actually use a length-N vector. For example, they often initialize arrays as zeros(N, 1), when they should use zeros(N)
The difference is important, and in almost all cases a vector is better.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
