[英]Flatten 3D array to 1D array
我们如何在java中将3D数组转换为1D数组?
我使用了下面的代码:
input :double [][][]S_p = { { { 1.1, 2.1 }, { 3.2, 4.1 } },
{ { 5.2, 6.1 }, { 7.1, 8.3 } } };
int rows = S_p.length;
int columns = S_p[0].length;
int depth = S_p[0][0].length;
double [] d1 = new double[row*columns*depth];
for(int i=0;i<depth;i++) {
for(int j=0;j<rows;j++){
for(int k=0;k<columns;k++) {
for(int ii=0;ii<rows*columns*depth;ii++) {
d1 [ii] = S_p[ depth *rows *i + columns *k +j];
}
}
}
out put b[]= {1.1, 2.1, 3.2 , 4.1 ...}
但这不起作用
在 Java 8 中,您可以简单地执行以下操作:
double[][][] vals = {{{1.1, 2.1}, {3.2, 4.1}}, {{5.2, 6.1}, {7.1, 8.3}}};
double[] test = Arrays.stream(vals)
.flatMap(Arrays::stream)
.flatMapToDouble(Arrays::stream)
.toArray();
System.out.println(Arrays.toString(test));
输出:
[1.1, 2.1, 3.2, 4.1, 5.2, 6.1, 7.1, 8.3]
解释:
Arrays.stream(vals)
创建一个Stream<double[][]>
。
.flatMap(Arrays::stream)
将其展平为Stream<double[]>
.flatMapToDouble
将Stream<double[]>
展平为DoubleStream
最后.toArray()
收集DoubleStream
中的所有值并返回一个double[]
。
你的方法是正确的,但你没有正确地乘以你的坐标。 确保您正确的一个好方法是使用霍纳方案的改编版: value_x + upper_bound_of_x * (value_y + upper_bound_of_y * ( ... ))
。
此外,最里面的循环是多余的,您应该能够使用上述方法计算S_p
的索引。
int rows = S_p.length;
int columns = S_p[0].length;
int depth = S_p[0][0].length;
double[] d1 = new double[rows * columns * depth];
for (int i = 0; i < depth; i++) {
for (int j = 0; j < rows; j++) {
for (int k = 0; k < columns; k++) {
d1[i + depth*(j + rows*(k))] = S_p[j][k][i];
}
}
}
我在这个问题上苦苦挣扎了一段时间。 给定一个 1D 数组 1D[height x width x depth] 和 3D 数组 array3D[height][width][depth],其中 x 高度为 y 宽度,z 为深度。 以下循环通过以下等式将 array3D 中的每个元素正确映射到 array1D:
x* width + y +z*( width * height)
用 C++ 编写代码:
for(int x=0; x<height;++x){
for (int y=0; y< width; ++y){
for (int z=0; z< depth; ++z){
array3D[x][y][z]=array1D[x* width + y +z*( width * height)];}}}
如果您正在进行一些计算,并且希望将数据保存在 1D 数组中,稍后将转换为您正在查看的 3D 数组:
for(int x=0; x<height;++x){
for (int y=0; y< width; ++y){
for (int z=0; z< depth; ++z){
array1D[x* width + y +z*( width * height)]=YourCalculatedData;}}}
PS:对于 Matlab,你应该从索引中减去 1,最后你应该在方程中加上 1,因为 Matlab 的循环从 1 开始,而不是 0
for x=1: height
for y=1: width
for z= 1:depth
volume(x,y,z)=rawdata((x-1)* width + (y-1 ) +(z-1)*( width * height)+1);
end
end
end
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.