How to create a 2D (9 by 9) array of Strings in Julia and initialize it
global AStrings = String(9,9)
Then assign a float64 , float64 to it
AStrings[i,j] = string(c[i]) * "," * string(c2[i])
Note c[i]
and c2[i]
are two float numbers
CodePudding user response:
You can avoid the headache of working out how to correctly instantiate an array by just using a comprehension:
julia> c = round.(rand(3), digits = 2); c2 = round.(rand(3), digits = 2);
julia> ["$x,$y" for x ∈ c, y ∈ c2]
3×3 Matrix{String}:
"0.2,0.21" "0.2,0.98" "0.2,0.04"
"0.32,0.21" "0.32,0.98" "0.32,0.04"
"0.29,0.21" "0.29,0.98" "0.29,0.04"
If you really do want to instantiate an "empty" array, you can do it like this:
julia> Matrix{String}(undef, 3, 3)
3×3 Matrix{String}:
#undef #undef #undef
#undef #undef #undef
#undef #undef #undef
Note that the type of the object I'm creating is Matrix{String}
(which is the same as Array{String, 2}
, not String
(which is the element type of the array)
CodePudding user response:
String(9,9)
is not a method in Julia. Type ?String
in the REPL to get help with a function. The $
as I used it below is called string interpolation. It is useful for constructing strings using other types, though what you wrote would also work. When typing code on forums like this, type ``` before and after the code so that it will be formatted nicely like mine.
julia> A = fill("", 9, 9)
9×9 Matrix{String}:
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
julia> x = 3.2
3.2
julia> y = 5.7
5.7
julia> A[2,3] = "$x, $y"
"3.2, 5.7"
julia> A
9×9 Matrix{String}:
"" "" "" "" "" "" "" "" ""
"" "" "3.2, 5.7" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""
"" "" "" "" "" "" "" "" ""