Concatenate Java Arrays
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, see How MATLAB Represents Java Arrays.
Two-Dimensional Horizontal Concatenation
This example horizontally concatenates two Java arrays. Create 2-by-3 arrays d1 and
d2.
d1 = javaArray('java.lang.Double',2,3); for m = 1:2 for n = 1:3 d1(m,n) = java.lang.Double(n*2 + m-1); end end d1
d1 =
java.lang.Double[][]:
[2] [4] [6]
[3] [5] [7]d2 = javaArray('java.lang.Double',2,2); for m = 1:2 for n = 1:3 d2(m,n) = java.lang.Double((n+3)*2 + m-1); end end d2
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 vectors J1 and J2.
import java.lang.Integer J1 = []; for ii = 1:3 J1 = [J1;Integer(ii)]; end J1
J1 =
java.lang.Integer[]:
[1]
[2]
[3]J2 = []; for ii = 4:6 J2 = [J2;Integer(ii)]; end J2
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.
import java.lang.Integer arr1 = 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[]:
[]
[]
[]