create a matrix dynamically with Julia

461 views
Skip to first unread message

Charles Novaes de Santana

unread,
Sep 11, 2014, 12:54:45 PM9/11/14
to julia...@googlegroups.com

Dear all,

I would like to create dynamically a matrix with two columns and N rows (where N can be any number between 0 and 1000). I thought I could do it by using the function "cat", but I am facing some problems with this.

My code:
A=[];
(...)
A=cat(1,A,[1 2]);

Is it a good way to create a matrix without defining its dimension a priori?

I was expecting that A would be a matrix 1x2, but I got the following error message:

ERROR: mismatch in dimension 2
 in cat_t at abstractarray.jl:689
 in cat at abstractarray.jl:666

I am using julia Version 0.4.0-dev+523 (2014-09-10 15:51 UTC)

Thank you in advance for any comment,

Charles

--
Um axé! :)

--
Charles Novaes de Santana, PhD
http://www.imedea.uib-csic.es/~charles

Douglas Bates

unread,
Sep 11, 2014, 1:38:14 PM9/11/14
to julia...@googlegroups.com
The short answer is vcat, as in

julia> A = Array(Int,(0,2))
0x2 Array{Int64,2}

julia> vcat(A,[1,2]')
1x2 Array{Int64,2}:
 1  2

Note that the ' is important as it cause the column vector [1,2] to be reshaped into a 1 by 2 matrix.

You may find it more effective to create the columns separately using push! and then use hcat to create the matrix when you are done, if this is feasible.  Using push! to append a new element onto the end of a vector is likely to be more efficient than vcat'ing matrices.

julia> c1 = Int[]; c2 = Int[]
0-element Array{Int64,1}

julia> for i in 1:10
          push!(c1,i)
          push!(c2,abs2(i))
       end

julia> hcat(c1,c2)
10x2 Array{Int64,2}:
  1    1
  2    4
  3    9
  4   16
  5   25
  6   36
  7   49
  8   64
  9   81
 10  100

Charles Novaes de Santana

unread,
Sep 11, 2014, 8:10:16 PM9/11/14
to julia...@googlegroups.com
Thank you very much, Douglas, for your great suggestions!

Best,

Charles
Reply all
Reply to author
Forward
0 new messages