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

Idiom #26 Create a 2-dimensional array

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

Illustration
let mut x = [[0.0; N] ; M];
let x = vec![vec![0.0f64; N]; M];
X : array (1 .. M, 1 .. N) of Float := (others => (others => 1.0));
#include <stdlib.h>
double **x=malloc(m*sizeof(double *));
int i;
for(i=0;i<m;i++)
	x[i]=malloc(n*sizeof(double));
const int m = 2;
const int n = 3;
double x[m][n];
#include <vector>
std::vector<std::vector<double>> x (m, std::vector<double> (n));
var x = new double[m, n];
auto x = new double[][](m, n);
var x = new List.generate(m, (_) => new List(n));
X = [{R * 1.0, C * 1.0} || R <- lists:seq(1, M), C <- lists:seq(1, N)].
func make2D(m, n int) [][]float64 {
	buf := make([]float64, m*n)

	x := make([][]float64, m)
	for i := range x {
		x[i] = buf[:n:n]
		buf = buf[n:]
	}
	return x
}
const m, n = 3, 4
var x [m][n]float64
x = [ [ j**(1/i) | j <- [1..n] ] | i <- [1..m] ]
1
var x = new Array(m);
for (var i = 0; i < m; i++) {
  x[i] = new Array(n);
}
-1
double[][] x = new double[m][n];
local array = setmetatable({},{
   __index = function(t1,k1)
      t1[k1] = setmetatable({},{
         __index = function(t2,k2)
            t2[k2] = 0
            return t2[k2]
         end
      })
      return t1[k1]
   end
})
$x = array();
$x = array_pad($x, m, 1);
for($i = 0; $i < count($x); $i++){
  $x[$i] = array();
  $x[$i] = array_pad($x[$i],n,1);
}
var _x: array[_m,_n] of Double;
my @array = (
   [ 1.0, 0.0, 0.0 ],
   [ 0.0, 1.0, 0.0 ],
   [ 0.0, 0.0, 1.0 ],
   "first three slots are a 3x3 identity matrix",
   "fourth and fifth slots contain strings"
);
   
x = [[0 for j in xrange(n)] for i in xrange(m)]
x = Array.new(m) { Array.new(n) }
(build-list m (lambda (x)
                (build-list n (lambda (y) 0))))

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

Idiom created by

programming-idioms.org

Related idioms