[英]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.