2014-01-30 92 views
1

我需要連接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 

將返回我下面的矩陣,

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

我怎麼能這樣做?

回答

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[][]陣列,他們有已經從創建的,你想要一個新的矩陣,那麼你可以添加另一種方法

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

我真的懷疑這是做這件事的最好方法。 – Sait

+1

「最好」是一個絕對術語,不清楚它是指性能,簡單還是別的。讓我們看看是否有人有「更好」的方式,或者確認沒有(明顯的)「更好」的方式。我總是樂於提出建議。 – Marco13

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