Creating Single-Entry Matrix?

Hello everyone!

I am new to Julia and I want to create single-entry matrices i.e.,

 1.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  1.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  1.0

Can please anyone shed some light on this? I tried using the following code

matrix1 = zeros(3, 3)
matrix1[1, 1] = 1.0
matrix1
matrix2 = zeros(3, 3)
matrix2[1, 1] = 1.0
matrix2
matrix3 = zeros(3, 3)
matrix3[1, 1] = 1.0
matrix3

But I want to do it in a more elegant and sleek way.

IMO there’s nothing wrong with the way you wrote it, but maybe you prefer something like the following:

one_hot(rows, cols, i, j) = [(r, c) == (i, j) for r in 1:rows, c in 1:cols]

matrix1 = one_hot(3, 3, 1, 1)
matrix2 = one_hot(3, 3, 2, 2)
matrix3 = one_hot(3, 3, 3, 3)
3 Likes

Maybe a sparse array if there is only going to be one value?

using SparseArrays
julia> A = dropzeros!(sparse([1,3], [2,3], [1.0,0.0]))
3Γ—3 SparseMatrixCSC{Float64, Int64} with 1 stored entry:
  β‹…   1.0   β‹…
  β‹…    β‹…    β‹…
  β‹…    β‹…    β‹…
2 Likes

FillArrays has a OneElement type that provides a non-materialized implementation:

julia> OneElement(1 #= value =#, (2,2) #= index =#, (3,3) #= size =#)
3Γ—3 OneElement{Int64, 2, Tuple{Int64, Int64}, Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}}:
 β‹…  β‹…  β‹…
 β‹…  1  β‹…
 β‹…  β‹…  β‹…

If you want a matrix from this, you may convert it:

julia> A = OneElement(1, (2,2), (3,3));

julia> Matrix(A)
3Γ—3 Matrix{Int64}:
 0  0  0
 0  1  0
 0  0  0
6 Likes

Just based on this approach:

julia> matrix2 = CartesianIndices((3, 3)) .== CartesianIndex(2, 2)
3Γ—3 BitMatrix:
 0  0  0
 0  1  0
 0  0  0

Cartesian indices are nice, just a bit verbose (due to the long names).

4 Likes