Logo

Programming-Idioms

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

Idiom #27 Create a 3-dimensional array

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

A 3D matrix with iteration variables i for rows, j for columns, k for depth
my @x;
my ($m, $n, $p) = (4,3,2);
my $v = 0;

foreach my $mx (0..$m-1) {
    foreach my $nx (0..$n-1) {
        foreach my $px (0..$p-1) {
            $x[$mx][$nx][$px] = $v++;
        }
    }
}

Sample boundaries are 4, 3, 2 and filled with integers. Perl will "autovivify" lists (i.e. add new elements) as they are referenced and grow the arrays on the fly.
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, ] ]
];

Array variables are only one-dimensional, but arrays-of-arrays using array references can represent multi-dimensional arrays.
X : array (1 .. M, 1 .. N, 1 .. P) of Float := (others => (others => (others => 1.0)));

New implementation...
< >
programming-idioms.org