How to concatenate arrays in Julia
Overview
An array is a comma-separated, ordered collection of elements. In this shot, we'll learn how to concatenate arrays using Julia.
We can concatenate arrays in Julia using the following functions.
vcat: This concatenates along dimension1.hcat: This concatenates along dimension2.
Syntax
hcat(pass comma separated arrays)vcat(pass comma separated arrays)
Parameters
Both the functions will take arrays as parameters.
Return value
Both the functions will return a new array after concatenation.
Example
a = [1 2 3 4 5]b = [6 7 8 9 10; 11 12 13 14 15]println("Displaying vcat concatenation")#concatenation along dimension 1display(vcat(a,b))c = [1; 2; 3; 4; 5]d = [6 7; 8 9; 10 11; 12 13; 14 15]println("\nDisplaying hcat concatenation")#concatenation along dimension 2display(hcat(c,d))
Explanation
- Line 1–2: We declare and initialize two arrays,
aandb. - Line 5: We concatenate the arrays
aandbalong the dimension1using thevcatfunction and display the returned new array. - Line 7–8: We declare and initialize two arrays,
candd. - Line 11: We concatenate the arrays
canddalong the dimension2using thehcatfunction and display the returned new array.