Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct matrix from row/column vectors in Julia

Tags:

matrix

julia

Given a function/expression that yields a single column, how to build a matrix from those columns in Julia? I tried the following (simplified example):

column(j) = [j, j, j]      # for example
my_matrix = Float64[column(j)[i] for i in 1:3, j in 1:4]

==> 3x4 Array{Float64,2}:
 1.0  2.0  3.0  4.0
 1.0  2.0  3.0  4.0
 1.0  2.0  3.0  4.0

The result is correct, but this is not what I want because the column-vector-expression is evaluated unnecessarily (once for every row).

I also tried this alternative approach:

[column(j) for j in 1:4]

==> 4-element Array{Array{Float64,1},1}:
 [1.0,1.0,1.0]
 [2.0,2.0,2.0]
 [3.0,3.0,3.0]
 [4.0,4.0,4.0]

But I found no way to convert or reshape this into the form I want (matrix with two dimensions instead of array of arrays).

How to achieve this in Julia?

like image 730
radioflash Avatar asked Dec 05 '22 22:12

radioflash


1 Answers

Have you tried hcat?:

julia> column(j) = [j, j ,j]
column (generic function with 1 method)

julia> my_matrix  = hcat([column(j) for j=1:4]...)
3x4 Array{Int64,2}:
 1  2  3  4
 1  2  3  4
 1  2  3  4

See hcat in Julia docs

like image 195
spencerlyon2 Avatar answered Mar 13 '23 08:03

spencerlyon2