Java Generic Matrix创建

时间:2018-03-16 04:06:10

标签: java arrays matrix arraylist

我想在java中创建一个泛型类型矩阵,其尺寸大小将被随机化。

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

用Java创建矩阵并不像R,或Matlab,甚至是C那样友好。非常强大的Java打字范例意味着必须定义或初始化所有内容。所以你不能简单地做整数[x] [y] [z]。除了数组之外,事情变得多毛。

不同之处在于在+ x,-x,+ y,-y,+ z,-z中移动的规则矩阵都基本相同。但是在Java中,如果要考虑矩阵的三维,它们是方向性的。这意味着您必须遍历X,然后遍历Y,然后遍历Z,始终按此顺序。然后移动说x + 1,你必须向下回z,向下回y,然后移动你的x位置,然后转身再次遍历y和z。 我不确定这是否合理。但这就是我必须考虑Java中的矩阵,否则我开始编码错误。

java的库专注于创建矩阵。你可以看看那里。 http://ejml.org/wiki/index.php?title=Main_Page

只是创建一个随机的数组数组(如上所述的伪数据矩阵)总体上看起来并不难。

import java.util.Random;

public class Rand
{
   public static void main(String[] args)
   {
      Random random = new Random();
     int dim1 = random.nextInt( 10 );
      int dim2 = random.nextInt( 10 );
      int dim3 = random.nextInt( 10 );

      int[][][] matrix = new int[dim1][dim2][];

      //use dim 3 when you do the specific the declaration for the 3rd dimension

   }

}

快速通过一些例子 -       Int myIntArray = new int [15]; 创建一个15成员的int数组,初始化为该类型的Default值,对于
为0       // - 分配值       myIntArray [2] = 5;       // = 0 0 5 0 0       myInt = myIntArray [2];       myInt = 5;

// @Initializing with values

   int[5] myIntArray = { 5, 10, 15, 20, 25 };
   int[] myIntArray = { 5, 10, 15, 20, 25 };

多维数组不像C中的矩阵。所有维度都是相同的类型。每个元素都是一个独立的数组。较早维度的每个数组元素都是一个数组。所有维度都是相同类型,每个元素都是一个独立的数组。 在Java中,除了多维数组之外的每个数组元素 最后一个维度是一个数组,而不是一个单独的元素        //两个暗淡的数组

  int[][] myIntArray2;
  //Or
  int myIntArray[][];

使用new运算符进行分配.Allocation初始化为DEFault type。在这种情况下,您正在初始化一个数组数组,因此DEFault type为null。

  int[][] myIntArray2d = new int[5][];
  myIntArray2d[3] = new int[5];

所以分配上面的数组,你得到

  null Null 0 Null Null
  []    []  0 []   [] 
  []    []  0 []   [] 
  []    []  0 []   [] 
  []    []  0 []   [] 

第一个dim中的空值Defaults为null - Default数组类型。在访问之前必须初始化第二个维度。

  char[][] charArray = new char[36][];

  //But I cant save anything into  

 charArray[4][0]; 

  //because it has not been initialized with a separate new statement.
  //This is why you leave the 3rd dim off until later.

 char[5]  = new char[5]; // WRONG
  char[] f = new char[5];
  //Now I can follow that with
  charArray[5][5] = 'a';  
  //or from about
  intArray[5][5][5]= 3;
  // But you cant declare the final dimension until later.

  int[3][] arr =  ( { 1, 2, 3 }, { 1, 2 }, { 5, 10, 15, 20 });
  //is an array[2] with 3 arrays
  int[][] arr =   { 1, 2, 3 }, { 1, 2 }, { 5, 10, 15, 20 }; 
  //is an array[2] with 3 arrays

这就是为什么你不能在Java中真正做矩阵。因为每个最终尺寸在技术上都可以变化。

将数组复制到变量中时 - 即

  charArrayvars = charArray[5]
  int[] Copies= { 0, 0, 0, 0, 0  } //as a pointer not the data.

  // This means that
  int[3] ArrayA = { 1, 2, 3 };
  Int[3] ArrayB = { 4, 5, 6 };
  ArrayB = Array A;

  //So ArrayB now references Array A.
   //Now if I set

  ArrayA[0] = 0; //then
   if( ArrayB[0] = 0 &&  ArrayA==ArrayB.){}
  //  The logic comparator really just shows they use the same reference.

我想虽然我会评估你的目标,看看是否还有其他方法。或者也许使用图书馆。因为像你一样的矩阵并不是Java的原生。有许多奇怪的行为,我做了一个糟糕的工作解释。