I have tried with split(), Vector() and a few other funny ideas, but I always get much more complicated Arrays. Is there an easy and computational unexpensive way to do that?
I appreciate any hint.
Thanks
This isn’t the most efficient possible approach because it allocates a new vector to hold the characters in each string, then throws that vector away after building the matrix. We can save some memory allocation by doing the permutedims and collect steps lazily:
julia> reduce(vcat, (permutedims(collect(s)) for s in a))
3×3 Array{Char,2}:
'1' '2' '3'
'4' '5' '6'
'a' 'b' 'c'
If you’re still concerned about performance, use BenchmarkTools.jl to measure it for your application.
Note that apart from the “nesting multiple functions approach” you can also always just write a bunch of simple loops:
function func(a)
n = length(a[1])
A = Matrix{Char}(undef,n,n) # preallocating the result
for i in 1:length(a) # looping over all strings
for (j, c) in enumerate(a[i]) # looping over all chars in a string
A[i, j] = c
end
end
return A
end
Since it’s Julia, it will be fast. On my machine I get
It’s a pity that you can’t write [c for c in v, v in a] or perhaps [c for c in a[i], i in eachindex(a)]. Because these go to Iterators.product, and it needs to know all the ranges before starting.
You can write this
[a[i][j] for i=1:length(first(a)), j=1:length(a)]
but it won’t behave well with non-ascii strings, like