How to create a vector of string elements from a combination of different strings and numbers?

I know how to combine a string "s" with a vector of integers i to get a string "si". For example, if I want to create the vector ["a1","a2","a3"], I do

 "a".* string.([1,2,3])
#3-element Vector{String}:
# "a1"
# "a2"
# "a3"

How can I create a vector using this same “procedure” but now with than one string “s”. For instance, if I want to create a vector ["a1","b1","a2","b2","a3","b3"]?

I tried the line above, but it failed.

["a","b"].*string.([1,2,3])

You need to broadcast between different dimensions (to solve it with broadcasting).

julia> vec(["a","b"].*string.([1,2,3]'))
6-element Vector{String}:
 "a1"
 "b1"
 "a2"
 "b2"
 "a3"
 "b3"
3 Likes

Thank you so much, @GunnarFarneback.

I don’t know if this is helpful but as noted in An exercise in DataFrames.jl transformation minilanguage | Blog by Bogumił Kamiński you can also remove the , in the number array.

vec(string.(["a", "b"], [1 2 3]))
6-element Vector{String}:
 "a1"
 "b1"
 "a2"
 "b2"
 "a3"
 "b3"

or without the vec you get a matrix

julia> string.(["x", "y"], [1 2 3])
2×3 Matrix{String}:
 "x1"  "x2"  "x3"
 "y1"  "y2"  "y3"

@GunnarFarneback if you have a moment could you explain what the ' operator is and how it works here?

I tried looking it up in the docs but only found the ‘adjoint’ function for retiring complex conjugates?

Here it’s just used as a shortcut to transform to a row vector.

julia> size([1,2,3]')
(1, 3)

The more general solution is to use permutedims, or for literals to use literal syntax to construct a vector along the desired dimension:

julia> size([1, 2, 3])
(3,)

julia> size([1 2 3])
(1, 3)

julia> size([1; 2; 3])
(3,)

julia> size([1;; 2;; 3])
(1, 3)

julia> size([1;;; 2;;; 3])
(1, 1, 3)

julia> size([1;;;; 2;;;; 3])
(1, 1, 1, 3)
1 Like

Got it thanks so much! Just wondering since these transformations yield different types

julia> typeof([1,2,3]')
LinearAlgebra.Adjoint{Int64, Vector{Int64}}

whereas

julia> typeof([1 2 3])
Matrix{Int64} (alias for Array{Int64, 2})

Are there use cases where the resultant type affects performance and we should choose one over the other? Or is that purely a function of whether the elements in the array itself are type stable?

Sorry if this is a silly question but just trying to get a better grasp of the fundamentals here.

1 Like

It’s a bit of a misuse (but a convenient one) to employ ' outside of a Linear Algebra context. The LinearAlgebra.Adjoint type is an example of a wrapper type which keeps the original array in the background but acts like some operation was applied. This is used with multiple dispatch for optimizations. E.g. x'' returns x itself without doing any work at all and x' * x is dispatched to a method which calls the dot function.

2 Likes