Shayan
Shayan

Reputation: 6295

Create a matrix with repetitive values from a slice of another matrix

Suppose I have this matrix:

julia> mat=[1 2 3;4 5 6]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

Now I want to achieve something like this using a standard function:

4×3 Matrix{Int64}:
 1  2  3
 1  2  3
 1  2  3
 1  2  3

Note that the important thing to me is using the slice! here the slice is mat[1, :]. I tried:

julia> fill(mat[1, :], 4,3)
4×3 Matrix{Vector{Int64}}:
 [1, 2, 3]  [1, 2, 3]  [1, 2, 3]
 [1, 2, 3]  [1, 2, 3]  [1, 2, 3]
 [1, 2, 3]  [1, 2, 3]  [1, 2, 3]
 [1, 2, 3]  [1, 2, 3]  [1, 2, 3]

julia> repeat(mat[1, :], inner=(4,1))
9×1 Matrix{Int64}:
 1
 1
 1
 1
 2
 2
 2
 2
 3
 3
 3
 3

Upvotes: 3

Views: 62

Answers (2)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

Or in this case just:

julia> repeat(mat[1:1, :], 4)
4×3 Matrix{Int64}:
 1  2  3
 1  2  3
 1  2  3
 1  2  3

(note 1:1 to avoid transposition)

Upvotes: 3

Shayan
Shayan

Reputation: 6295

I was trying to find a workaround for this problem, and after reading the repeat's documentation, I found my way:

julia> repeat(mat[1, :]', inner=(4,1))
3×3 Matrix{Int64}:
 1  2  3
 1  2  3
 1  2  3
 1  2  3

The point was the mat[1, :] returns a Vector. Then applying repeat on it wouldn't lead to the expected output. Then transposing the vector is crucial in this case.

Upvotes: 3

Related Questions