矩阵连接jama

时间:2014-01-30 10:11:10

标签: java jama

我需要在JAMA中连接两个矩阵。

double[][] m1  = {{1,1,1}, {1,1,1}};    
double[][] m2 =  {{2,2,2}, {2,2,2}, {2,2,2}};

Matrix mm1 = new Matrix(m1);
Matrix mm2 = new Matrix(m2);

我想做以下事情,

Matrix mm3 = [ mm1; mm2; ] // in Matlab syntax

将返回以下Matrix,

1 1 1
1 1 1
2 2 2
2 2 2
2 2 2

我该怎么做?

2 个答案:

答案 0 :(得分:2)

假设结果矩阵的行应该是原始矩阵行的副本

import java.util.Arrays;

public class MatrixConcat
{
    public static void main(String[] args)
    {
        double[][] m1  = {{1,1,1}, {1,1,1}};
        double[][] m2 =  {{2,2,2}, {2,2,2}, {2,2,2}};

        double[][] m3 = combine(m1, m2);

        System.out.println("m1");
        print(m1);
        System.out.println("m2");
        print(m2);
        System.out.println("m3");
        print(m3);

    }

    private static void print(double m[][])
    {
        for (int i=0; i<m.length; i++)
        {
            System.out.println(Arrays.toString(m[i]));
        }
    }

    private static double[][] combine(double m0[][], double m1[][])
    {
        double result[][] = new double[m0.length+m1.length][];
        for (int i=0; i<m0.length; i++)
        {
            result[i] = m0[i].clone();
        }
        for (int i=0; i<m1.length; i++)
        {
            result[m0.length+i] = m1[i].clone();
        }
        return result;
    }
}

编辑:假设您只有矩阵,而不是它们已经创建的double[][]数组,并且您想要一个新的Matrix,那么您可以添加另一个方法

private static Matrix concat(Matrix m0, Matrix m1)
{
    return new Matrix(combine(m0.getArray(), m1.getArray()));
}

答案 1 :(得分:1)

我在JamaUtils类中找到了这个解决方案:

 /**
 * Appends additional rows to the first matrix.
 *
 * @param m the first matrix.
 * @param n the matrix to append containing additional rows.
 * @return a matrix with all the rows of m then all the rows of n.
 */
public static Matrix rowAppend(Matrix m, Matrix n) {
    int mNumRows = m.getRowDimension();
    int mNumCols = m.getColumnDimension();
    int nNumRows = n.getRowDimension();
    int nNumCols = n.getColumnDimension();

    if (mNumCols != nNumCols)
        throw new IllegalArgumentException("Number of columns must be identical to row-append.");

    Matrix x = new Matrix(mNumRows + nNumRows, mNumCols);
    x.setMatrix(0, mNumRows - 1, 0, mNumCols - 1, m);
    x.setMatrix(mNumRows, mNumRows + nNumRows - 1, 0, mNumCols - 1, n);

        return x;
}