Best practices - initialize a matrix

Hello,

I’m doing my first steps in julia and using the v1.0.1, and I wondered what is the best practice to initialize a large matrix.

I’m just initializing in the following way: b = Array{Float64}(undef,dim). But i know there are anothers ways to do that, such as: b = Array{Union{Nothing, String}}(nothing, dim), or use the function spzeros() that creates a sparse matrix with zeros.

What is the best practice? Most of time i just want to initialize the matrix structure, not all the matrix entries.

Thank you,
Tiago

This really depends on what you are going to do with the matrix down the line, so maybe you can mention something about that?

1 Like

Yes, you’re right, What I am trying to do is the following:

x = h:h:L-h
F = 2*sin.(X) - sin.(2*X)

B = Array{Float64}(undef,n,n)  
#or B = Array{Union{Nothing, String}}(nothing, n, n) or B = spzeros(n, n) 

B[n, 1:n] = F

I construct a vector f, and I just initialize the last row of B with f. Then I just fill the whole matrix B with a loop.

What is the best way to do such thing? My background it’s Matlab and perhaps I am not thinking in the julia way.

Thank you for the patience,
Tiago

It sounds like the goal is to have a matrix of only Float64 that have all entries stored? Then I would definitely not use a sparse matrix, and I would not use Union{Float64, Nothing} either. Your plan with using Matrix{Float64}(undef, n, n) and then setting the elements in a loop sounds perfectly reasonable.

Note that

can be written as

B[end, :] = F
2 Likes

Oh yes, thank you. I forgot to use the end command and the colon :.

So, if I want to use the spzeros() function it’s only in the case that you have a lot of zeros in the matrix. Ok!

Appreciate the help, thank you :slight_smile: