Logo

Programming-Idioms

  • C++
  • Ruby
  • Scheme
  • Python
  • Java

Idiom #26 Create a 2-dimensional array

Declare and initialize a matrix x having m rows and n columns, containing real numbers.

double[][] x = new double[m][n];

Initial values are 0.0
m and n need not be known at compile time
import java.math.BigDecimal;
BigDecimal x[][] = new BigDecimal[m][n];
#include <array>
::std::array<::std::array<int, n>, m> x;

n and m is constexpr.
#include <vector>
std::vector<std::vector<double>> x (m, std::vector<double>(n));
x = Array.new(m) { Array.new(n) }
(build-list m (lambda (x)
                (build-list n (lambda (y) 0))))

The (lambda (y) 0) isn't strictly necessary, it just initializes the values in the matrix to 0.
x = [[0] * n for _ in range(m)]

Do not just "multiply by m", which would duplicate the references to the inner arrays.
from itertools import repeat
x = [*repeat([.0] * n, m)]
x = []
for i in range(m):
    x.append([.0] * n)
X : array (1 .. M, 1 .. N) of Float := (others => (others => 1.0));

New implementation...