Programming-Idioms

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
let x = vec![vec![vec![0.0f64; P]; N]; M];
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));
	}
}
#include <vector>
std::vector<std::vector<std::vector<double>>> x (m, std::vector<std::vector<double>> (n, std::vector<double> (p)));
var multidimensionalArray = new double[m, n, p];
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)].
  real, dimension(:,:,:), allocatable :: x

  allocate (x(m,n,p))
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] ]
const x = new Array(m).fill(
  new Array(n).fill(
    new Array(p).fill(Math.random())
  )
)
double[][][] x = new double[m][n][p];
(defparameter *x*
  (make-array (list m n p)
              :element-type 'double-float
              :initial-element 0.0d0))
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;
my $array3d = [
    [ [ 1, 0, 1 ],
      [ 0, 0, 0 ],
      [ 1, 0, 1 ] ],
    [ [ 0, 0, 0 ],
      [ 0, 2, 0 ],
      [ 0, 0, 0 ] ],
    [ [ 3, 0, 3, ],
      [ 0, 0, 0, ],
      [ 3, 0, 3, ] ]
];
import numpy
x = numpy.zeros((m,n,p))
x = [[[0 for k in range(p)] for j in range(n)] for i in range(m)]
x = Array.new(m) { Array.new(n) { Array.new(p) } }

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

Idiom created by

programming-idioms.org

Related idioms