A for loop should be extremely efficient. If that solution is already working for you, then you’re already done!

Is constructing this matrix actually a performance bottleneck? If so, have you considered not constructing it at all? For example, you could create your own AbstractArray which stores only the non-zero entries and implement Base.getindex(::MyNewArrayType, i) to return the right nonzero entry or zero as appropriate. Or, for that matter, can you just use SparseArrays, which already do exactly that?

A lot of these questions will be easier to answer if you can tell us more about what your performance bottlenecks are and what you’re planning to do with the resulting data structure.

Hey again, so it isn’t really a performance bottleneck for me, I just enjoy seeing/learning how others will approach a similar problem - sometimes I have experienced that I make a complex and working solution and then some one pops in, and says you can just do this, this and that. Always fun for me to learn more - I will have a look at sparse arrays and trying to define something as you describe.

Thank you very much for your code bit - I modified it slightly, so that it also determines and preallocates the right type:

function build_nD(N,dim)
typ = eltype(N)
out = Array{typ,2}(fill(0,dim,dim*length(N)))
for i = 1:dim
for j = 1:length(N)
out[i,(j-1)dim+i] = N[j]
end
end
out
end

This was necessary since I was using SymEngine and symbolic variables cannot be inserted into int/float arrays. It was much more compact than my first for loop, so I am pretty happy with it.