Matthijs
Matthijs

Reputation: 21

How can I concatenate multiple rows in a matrix

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

Upvotes: 1

Views: 2369

Answers (2)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95579

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);
}

Upvotes: 2

python dude
python dude

Reputation: 8358

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/).

Upvotes: 0

Related Questions