How to append a vector to Julia matrix as a row?

17,017

Solution 1

That is because your matrix sizes don't match. Specifically v does not contain enough columns to match m. And its transposed

So this doesnt work

m = Matrix(0, 3)
v = [2,3]
m = cat(1, m, v)  # or a = [m; v]
>> ERROR: DimensionMismatch("mismatch in dimension 2 (expected 3 got 1)")

whereas this does

m = Matrix(0, 3)
v = [2 3 4]
m = cat(1, m, v)  # or m = [m; v]
>> 1x3 Array{Any,2}:
>>   2  3  4

and if you run it again it creates another row

m = cat(1, m, v)  # or m = [m; v]
>> 2x3 Array{Any,2}:
>>   2  3  4
>>   2  3  4

Solution 2

Use the vcat (concatenate vertically) function:

help?> vcat
search: vcat hvcat VecOrMat DenseVecOrMat StridedVecOrMat AbstractVecOrMat levicivita is_valid_char @vectorize_2arg

  vcat(A...)

  Concatenate along dimension 1

Notice you have to transpose the vector v, ie. v', else you get a DimensionMismatch error:

julia> v = zeros(3)
3-element Array{Float64,1}:
 0.0
 0.0
 0.0

julia> m = ones(3, 3)
3x3 Array{Float64,2}:
 1.0  1.0  1.0
 1.0  1.0  1.0
 1.0  1.0  1.0

julia> vcat(m, v')    # '
4x3 Array{Float64,2}:
 1.0  1.0  1.0
 1.0  1.0  1.0
 1.0  1.0  1.0
 0.0  0.0  0.0

julia> v'    # '
1x3 Array{Float64,2}:
 0.0  0.0  0.0

julia> vcat(m, v)
ERROR: DimensionMismatch("mismatch in dimension 2 (expected 3 got 1)")
 in cat_t at abstractarray.jl:850
 in vcat at abstractarray.jl:887

Note: the comments; # ' are there just to make syntax highlighting work well.

Share:
17,017
becko
Author by

becko

Updated on July 18, 2022

Comments

  • becko
    becko almost 2 years

    I have an empty matrix initially:

    m = Matrix(0, 3)
    

    and a row that I want to add:

    v = [2,3]
    

    I try to do this:

    [m v]
    

    But I get an error

     ERROR: ArgumentError: number of rows of each array must match
    

    What's the proper way to do this?

  • Admin
    Admin about 8 years
    Or if you want to maintain your v = [2,3,4] format you can append the row using m = [m; v'].