This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #26 Create a 2-dimensional array
Declare and initialize a matrix x having m rows and n columns, containing real numbers.

- Ada
- C
- C
- Clojure
- C++
- C++
- C#
- D
- Dart
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Go
- Go
- Haskell
- JS
- JS
- Java
- Java
- Kotlin
- Lisp
- Lua
- Lua
- Obj-C
- PHP
- PHP
- Pascal
- Perl
- Python
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
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
}
This works even when m, n are not compile-time constants.
This code allocates one big slice for the numbers, plus one slice for x itself.
The same function would have to be rewritten, for types other than float64.
This code allocates one big slice for the numbers, plus one slice for x itself.
The same function would have to be rewritten, for types other than float64.
const m, n = 3, 4
var x [m][n]float64
m, n must be constant for this syntax to be valid.
Here x is of type [3][4]float64, it is not a slice.
Here x is of type [3][4]float64, it is not a slice.
func make2D[T any](m, n int) [][]T {
buf := make([]T, m*n)
x := make([][]T, m)
for i := range x {
x[i] = buf[:n:n]
buf = buf[n:]
}
return x
}
This generic func works for any type parameter T.
m, n do not need to be compile-time constants.
This code allocates one big slice for the elements, plus one slice for x itself.
m, n do not need to be compile-time constants.
This code allocates one big slice for the elements, plus one slice for x itself.
double[][] x = new double[m][n];
Initial values are 0.0
m and n need not be known at compile time
m and n need not be known at compile time
val x = Array(m, { DoubleArray(n) })
The type of x is Array<DoubleArray>. In other words, an array of arrays.
local x = setmetatable({},{
__index = function(t1,k1)
t1[k1] = setmetatable({},{
__index = function(t2,k2)
t2[k2] = 0
return t2[k2]
end
})
return t1[k1]
end
})
2D arrays are tables of tables (tables are hashmaps).
Use metatable to lazy initialize each row (t1[k1]) and each column (t2[k2]) the first time it's accessed.
See http://www.programming-idioms.org/idiom/27/create-a-3-dimensional-array/1675/lua for a more "standard" way.
Use metatable to lazy initialize each row (t1[k1]) and each column (t2[k2]) the first time it's accessed.
See http://www.programming-idioms.org/idiom/27/create-a-3-dimensional-array/1675/lua for a more "standard" way.
$m = 3;
$n = 4;
$x = array_map(
function () use ($m) { return array_fill(0, $m, 0); },
range(1, $n)
);
PHP is pretty lackadaisical about forward declarations, but this is a clean functional approach to bang one out pretty painlessly.
x = [[0] * n for _ in range(m)]
Do not just "multiply by m", which would duplicate the references to the inner arrays.