views:

195

answers:

2

In Java I would like to concatenate an array (a[], fixed length) to an array of the same length, to create a matrix M[2][length of a]. This way I would like to subsequently paste more of those arrays onto the matrix. (Comparable to the Matlab vertcat function..C=[A;B]) Is this possible? Thanks

+2  A: 

Yes, it is possible. Here is an example:

public class Main
{
    public static void main(String[] args)
    {
        int[] A = new int[]{1, 2, 3};
        int[] B = new int[]{4, 5, 6};
        int[][] M  = new int[2][];
        M[0] = A;
        M[1] = B;

        for ( int i = 0; i < 2; i ++ ){
             for (int j = 0; j < M[i].length; j++ ){
                 System.out.print(" "+ M[i][j]);
             }
             System.out.println("");
        }
    }
}

The above prints out:

 1 2 3
 4 5 6

We can do even better than that, though. If you are using Java 5 or higher, use:

public static int[][] vertcat(int[]... args){
   return args;
}

Then you can write:

int[][] M = vertcat(A,B);

And it will work for any number of arguments.

Edit
The above method stuffs the original arrays into another array, which means that any modification to the result will affect the original arrays, which may be undesireable. Use the following to copy the values:

public static int[][] copyMatrix(int[][] original){
    if ( (original==null) || (original.length==0) || (original[0].length == 0) ){
        throw new IllegalArgumentException("Parameter must be non-null and non-empty");
    }
    rows = original.length;
    cols = original[0].length;
    int[][] cpy = new int[rows][cols];
    for ( int row = 0; row < rows; row++ ){
       System.arraycopy(original[row],0,cpy[row],0,cols);
    }
    return cpy;
}

If you want vertcat to return a copy rather than the original, you can redefine it as:

public static int[][] vertcat(int[]... args){
   return copyMatrix(args);
}
Michael Aaron Safyan
but keep in mind that the *matrix* elements are still the original arrays. Any changes made to the values of the matrix will be reflected in the original arrays, and the same backwards.
Carlos Heuberger
@Carlos, yes that's correct. Thank you for noting that.
Michael Aaron Safyan
A: 

As far as I know, Java has no built-in support for matrices and matrix-related operations. I would either use a 2D array, write my own Matrix wrapper class (in simpler cases) or hunt down a good Matrix library (e.g. http://jmathtools.berlios.de/).

python dude