ConcatenateJavaArrays
To concatenate arrays of Java®objects, use the MATLAB®cat
function or the square bracket ([]
) operators.
You can concatenate Java objects only along the first (vertical) or second (horizontal) axis. For more information, seeHow MATLAB Represents Java Arrays.
Two-Dimensional Horizontal Concatenation
This example horizontally concatenates two Java arrays. Create 2-by-3 arraysd1
andd2
.
d1 = javaArray('java.lang.Double',2,3);form = 1:2forn = 1:3 d1(m,n) = java.lang.Double(n*2 + m-1);endendd1
d1 = java.lang.Double[][]: [2] [4] [6] [3] [5] [7]
d2 = javaArray('java.lang.Double',2,2);form = 1:2forn = 1:3 d2(m,n) = java.lang.Double((n+3)*2 + m-1);endendd2
d2 = java.lang.Double[][]: [8] [10] [12] [9] [11] [13]
Concatenate the two arrays along the second (horizontal) dimension.
d3 = cat(2,d1,d2)
d3 = java.lang.Double[][]: [2] [4] [6] [8] [10] [12] [3] [5] [7] [9] [11] [13]
Vector Concatenation
This example shows the difference between row and column concatenation for vectors. Create two vectorsJ1
andJ2
.
importjava.lang.IntegerJ1 = [];forii = 1:3 J1 = [J1;Integer(ii)];endJ1
J1 = java.lang.Integer[]: [1] [2] [3]
J2 = [];forii = 4:6 J2 = [J2;Integer(ii)];endJ2
J2 = java.lang.Integer[]: [4] [5] [6]
Concatenate by column. Horizontally concatenating two Java vectors creates a longer vector, which prints as a column.
Jh = [J1,J2]
Jh = java.lang.Integer[]: [1] [2] [3] [4] [5] [6]
Concatenate by row. Vertically concatenating two Java vectors creates a 2-D Java array.
Jv = [J1;J2]
Jv = java.lang.Integer[][]: [1] [2] [3] [4] [5] [6]
Note
Unlike MATLAB, a 3x1 Java array is not the same as a Java vector of length 3. Create a 3x1 array.
importjava.lang.Integerarr1 = javaArray('java.lang.Integer',3,1)
arr1 = java.lang.Integer[][]: [] [] []
Create a vector of length 3.
arr2 = javaArray('java.lang.Integer',3)
arr2 = java.lang.Integer[]: [] [] []