This language bar is your friend. Select your favorite languages!

Idiom #27 Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

Illustration
#include <vector>
std::vector<std::vector<std::vector<double>>> x (m, std::vector<std::vector<double>> (n, std::vector<double> (p)));
X : array (1 .. M, 1 .. N, 1 .. P) of Float := (others => (others => (others => 1.0)));
#include <stdlib.h>
double ***x=malloc(m*sizeof(double *));
int i,j;
for(i=0;i<m;i++)
{
	x[i]=malloc(n*sizeof(double));
	for(j=0;j<n;j++)
	{
		x[i][j]=malloc(p*sizeof(double));
	}
}
auto x = new real[][][](m, n, p);
var x = new List.generate(m, (_) => 
                new List.generate(n, (_) => 
                    new List.filled(p, 0.0), 
                    growable: false), 
                growable: false);
X = array(M, N, P).

-spec array(pos_integer(), pos_integer(), pos_integer()) -> [[[float()]]].
array(M, N, P) -> [array(M, N)  || _ <- lists:seq(1, P)].
array(M, N) -> [array(M) || _ <- lists:seq(1, N)].
array(M) -> [rand:uniform() || _ <- lists:seq(1, M)].
const m, n, p = 2, 2, 3
var x [m][n][p]float64
func make3D(m, n, p int) [][][]float64 {
	buf := make([]float64, m*n*p)

	x := make([][][]float64, m)
	for i := range x {
		x[i] = make([][]float64, n)
		for j := range x[i] {
			x[i][j] = buf[:p:p]
			buf = buf[p:]
		}
	}
	return x
}
x = [ [ [ k**(i/j) | k<-[1..p] ] | j<-[1..n] ] | i<-[1..m] ]
var x = 
    [].fill(
        [].fill(
            [].fill(0, 0, p),
            0,
            n
        ),
        0,
        m
    );
double[][][] x = new double[m][n][p];
local x = {}
for i=1,m do
   x[i] = {}
   for j=1,n do
      x[i][j] = {}
      for k=1,p do
         x[i][j][k] = 0
      end
   end
end
$x = array_fill(0, $m, array_fill(0, $n, array_fill(0,$p,0)));
var x: array [m,n,p] of double;
import numpy
x = numpy.zeros((m,n,p))
x = [[[0 for k in xrange(p)] for j in xrange(n)] for i in xrange(m)]
x = Array.new(m) { Array.new(n) { Array.new(p) } }
let x = vec![vec![vec![0.0f64; P]; N]; M];

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms