For the complete documentation index, see llms.txt. This page is also available as Markdown.

Creating NDArrays

All methods for creating INDArrays — factory methods, from Java arrays, random, combining, and typed creation

Overview

Every NDArray in ND4J is created through static factory methods on org.nd4j.linalg.factory.Nd4j. There is no public constructor. This page covers every creation path available in M2.1, from simple zeros to multi-dimensional arrays built from Java primitives, combined arrays, and typed arrays.

Key M2.1 change: The global DataBuffer.Type enum used to configure a single default type for the whole JVM has been replaced by the per-array DataType enum. Each array carries its own type, and the default type for new arrays is FLOAT. See Typed Creation for details.

Standard imports used throughout this page:

import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.buffer.DataType;

Factory Methods

Nd4j.zeros()

Creates an array filled entirely with zeros. The shape is given as a varargs list of long dimensions, or as a long[] shape array.

// 1D: five zeros
INDArray v = Nd4j.zeros(5);
System.out.println(v);
// [         0,         0,         0,         0,         0]

// 2D: 3 rows, 4 columns
INDArray m = Nd4j.zeros(3, 4);
System.out.println(m);
// [[         0,         0,         0,         0],
//  [         0,         0,         0,         0],
//  [         0,         0,         0,         0]]

// Shape given as an array
long[] shape = {2, 3, 4};
INDArray t = Nd4j.zeros(shape);
// rank 3, shape [2, 3, 4], 24 elements, all zero

The default DataType is FLOAT. To request a specific type pass it as the first argument:

Nd4j.ones()

Creates an array filled entirely with ones. Same shape syntax as zeros.

Nd4j.valueArrayOf()

Creates an array of a given shape where every element has the same scalar value. This is the most direct way to fill an array with a constant without a follow-up scalar add.

You can also use zeros combined with in-place operations for derived fill values:

Random Arrays

Uniform random: Nd4j.rand()

Produces an array with values drawn uniformly from [0, 1).

Gaussian random: Nd4j.randn()

Produces an array with values drawn from a standard normal distribution N(0, 1) — mean zero, standard deviation one.

Seeding the random number generator

For reproducible experiments, seed ND4J's random number generator before creating random arrays:

From Java Arrays

Nd4j.createFromArray()

createFromArray is the modern, overloaded method for creating NDArrays directly from Java primitive arrays. It infers the shape automatically from the array dimensions and has overloads for double, float, int, and long in 1D through 4D.

1D arrays:

2D arrays:

3D and 4D arrays follow the same pattern — createFromArray has overloads for float[][][], double[][][], int[][][], long[][][], and their 4D equivalents.

Nd4j.create() from flat Java arrays

The older Nd4j.create methods accept a flat Java array and an optional explicit shape. These remain fully supported.

Higher-dimensional arrays from nested Java arrays

For 3D and deeper structures using raw Java arrays, the standard approach is to flatten the nested array into a 1D buffer and supply the shape explicitly:

The 'c' argument specifies C (row-major) order. Use 'f' for Fortran (column-major) order. For 3D and 4D input, createFromArray is generally easier to use and should be preferred where available.

From Other NDArrays

dup() — deep copy

dup() returns a completely independent copy of the array. The copy and the original share no underlying memory — modifying one does not affect the other.

By default dup() uses C order. To dup with a specific memory order:

getRow() and getColumn() — views

getRow(int i) and getColumn(int j) return views of the original array. Modifying the returned view modifies the original.

To get an independent copy of a row, use getRow(i).dup():

Views from get() and NDArrayIndex

get(NDArrayIndex...) returns a view of any sub-array:

These are views — use .dup() when you need an independent copy.

Combining Arrays

Nd4j.hstack() — horizontal stack

hstack concatenates arrays along dimension 1 (columns). All input arrays must have the same number of rows.

Nd4j.vstack() — vertical stack

vstack concatenates arrays along dimension 0 (rows). All input arrays must have the same number of columns.

Both hstack and vstack accept varargs, so you can stack more than two arrays at once:

Nd4j.concat() — concatenate along any dimension

concat(int dimension, INDArray... arrays) generalises hstack and vstack to any dimension.

concat also works on higher-rank arrays. For a set of rank-3 arrays with shape [batch, height, width], concatenating on dimension 0 combines them along the batch axis.

Nd4j.pad() — pad an array

pad surrounds an array with constant values (zero by default). The padding amounts are specified per dimension.

The PadMode.CONSTANT mode fills the padded region with zeros. Other modes (e.g., PadMode.REFLECT, PadMode.SYMMETRIC) mirror existing values into the padded region.

Special Creation Methods

Nd4j.eye() — identity matrix

Creates an NxN identity matrix: ones on the main diagonal, zeros everywhere else.

Nd4j.linspace() — evenly spaced values

linspace(start, stop, count) generates count evenly spaced values from start to stop inclusive.

Linspace is commonly combined with reshape to produce initialised matrices of arbitrary shape:

Nd4j.arange() — integer-spaced values

arange creates a 1D array of consecutive integers, following the same convention as NumPy's arange.

arange is often combined with reshape to produce structured matrices:

Nd4j.diag() — diagonal matrix or vector

diag has two complementary behaviours depending on the rank of the input:

  • If the input is a vector (rank 1), diag produces an NxN matrix with those values on the main diagonal.

  • If the input is a matrix (rank 2), diag extracts the main diagonal and returns a vector.

Typed Creation

The DataType enum

In M2.1, every INDArray carries its own DataType. You can read it at any time:

Passing DataType to creation methods

All major creation methods accept a DataType as the first argument. When omitted, the default is FLOAT.

Casting an existing array

If you already have an array but need a different type, use castTo:

castTo returns a new array; the original is unchanged.

Setting the global default type

To change the default for all subsequent array creation in your application, call this once during startup before creating any arrays:

The two arguments are the default floating-point type and the default integer type respectively. After this call, Nd4j.zeros(3, 4) will produce a DOUBLE array.

Migration from beta4: DataBuffer.Type is gone

In releases prior to M2.1, the type was controlled globally via DataBuffer.Type:

In M2.1, DataBuffer.Type no longer exists. Use per-array DataType arguments instead:

Empty Arrays

Nd4j.empty(DataType) creates a zero-element array of the given type. This is useful as a sentinel value or as a placeholder that can be detected with isEmpty().

Empty arrays of a specific shape (with zero in one or more dimensions) can be constructed with zeros by including a zero dimension:

Quick Reference

Goal
Method

All zeros

Nd4j.zeros(rows, cols)

All ones

Nd4j.ones(rows, cols)

Constant fill

Nd4j.valueArrayOf(shape, value)

Uniform random [0,1)

Nd4j.rand(rows, cols)

Gaussian N(0,1)

Nd4j.randn(rows, cols)

From double[][]

Nd4j.createFromArray(double[][])

From float[][]

Nd4j.createFromArray(float[][])

From int[][]

Nd4j.createFromArray(int[][])

From long[][]

Nd4j.createFromArray(long[][])

Row vector from double[]

Nd4j.create(double[])

Column vector from double[]

Nd4j.create(double[], new int[]{n,1})

3D+ from nested Java array

ArrayUtil.flattenDoubleArray + Nd4j.create(flat, shape, 'c')

Deep copy

arr.dup()

Row view

arr.getRow(i)

Row copy

arr.getRow(i).dup()

Horizontal stack

Nd4j.hstack(a, b)

Vertical stack

Nd4j.vstack(a, b)

Concat along axis

Nd4j.concat(dim, a, b)

Pad with zeros

Nd4j.pad(arr, padding, Nd4j.PadMode.CONSTANT)

Identity matrix

Nd4j.eye(n)

Evenly spaced values

Nd4j.linspace(start, stop, count)

Integer range

Nd4j.arange(start, stop)

Diagonal matrix/vector

Nd4j.diag(arr)

Typed zeros

Nd4j.zeros(DataType.DOUBLE, rows, cols)

Empty array

Nd4j.empty(DataType.FLOAT)

Change type

arr.castTo(DataType.DOUBLE)


See Tensors and NDArrays for the full description of rank, shape, stride, and memory layout. See the Operations page for how to manipulate and compute with arrays once created.

Last updated

Was this helpful?