这是 Matlab 中定义的尺寸函数,如文档中所示:
m = size(X,dim) returns the size of the dimension of X specified by scalar dim.
1)鉴于 X 是 java 中的单个数组,我将如何使用 Java 复制此方法。
Matlab 只是将矩阵和 n 维数据线性存储在一个数组中。每个维度的大小与数组一起保存,因此当您进行非线性索引时,Matlab 知道要返回哪个元素(例如A(3,5),对于 5x5 矩阵,Matlab 知道它应该返回的元素A(23)是3+(5-1)*5)。
因此,在 java 中,如果数组具有 size N1xN2x...xNN,并且您正在寻找 element: (X1,X2,...,XN),则应该在数组中找到具有 position:的元素X1+(X2-1)*N1+(X3-1)*N1*N2+ ... +(XN-1)*NN-1*..*N1...
如果你只想要数组的大小(任何维度),你有一个属性Array.length。
来自JLS:
公共最终字段长度,其中包含数组的组件数。长度可以是正数或零。
例如:
int[] arr = new int[10];
int length = arr.length; //would obtain 10
Java 中的数组只有一维:元素的数量。您只需使用属性即可访问它Array.length。对于更复杂的容器(例如ArrayList),您通常可以使用成员函数size()。
int[] array = new int[5];
int arrayLength = array.length; //arrayLength == 5
ArrayList<int> arrayList = new ArrayList();
arrayList.add(1);
arrayList.add(2);
int arrayListLength = arrayLis.size(); //arrayListLength == 2