Reputation: 20794
I need to construct a matrix in Julia by appending rows. The idea is this:
mat = [] # initialize empty mat
for i = 1:5
x, y = f(i), g(i) # here f and g are previously defined functions
mat = [mat; [x y]]
end
This doesn't work, I get an error:
ERROR: DimensionMismatch("mismatch in dimension 2 (expected 2 got 1)")
in the line where I try to append to mat
. I am new to Julia. How can I accomplish what I want?
Upvotes: 1
Views: 1150
Reputation: 18227
The initial mat = []
creates a 1-dim array. The proper way to initialize would be mat = reshape([],0,2)
. Perhaps typing the array is also recommended. For example, mat = Array{Float64}(0,2)
.
Concatenating rows this way is costly because of the column-first ordering of arrays in memory used by Julia. Consider defining the full array and assigning elements in the loop. Possibly mat = Array{Float64}(5,2)
.
Also, a commenter suggested Matrix(0,2)
which is another method to initialize a 0x2 matrix.
Upvotes: 4