Skip to main content

taichi.lang.matrix#

class taichi.lang.matrix.Matrix(arr, dt=None, is_ref=False, ndim=None)#

Bases: taichi.lang.common_ops.TaichiOperations

The matrix class.

A matrix is a 2-D rectangular array with scalar entries, it’s row-majored, and is aligned continuously. We recommend only use matrix with no more than 32 elements for efficiency considerations.

Note: in taichi a matrix is strictly two-dimensional and only stores scalars.

Parameters:
  • arr (Union[list, tuple, np.ndarray]) – the initial values of a matrix.

  • dt (primitive_types) – the element data type.

  • ndim (int optional) – the number of dimensions of the matrix; forced reshape if given.

Example:

use a 2d list to initialize a matrix

>>> @ti.kernel
>>> def test():
>>>     n = 5
>>>     M = ti.Matrix([[0] * n for _ in range(n)], ti.i32)
>>>     print(M)  # a 5x5 matrix with integer elements

get the number of rows and columns via the `n`, `m` property:

>>> M = ti.Matrix([[0, 1], [2, 3], [4, 5]], ti.i32)
>>> M.n  # number of rows
3
>>> M.m  # number of cols
>>> 2

you can even initialize a matrix with an empty list:

>>> M = ti.Matrix([[], []], ti.i32)
>>> M.n
2
>>> M.m
0
all(self)#

Test whether all element not equal zero.

Returns:

True if all elements are not equal zero, False otherwise.

Return type:

bool

Example:

>>> v = ti.Vector([0, 0, 1])
>>> v.all()
False
any(self)#

Test whether any element not equal zero.

Returns:

True if any element is not equal zero, False otherwise.

Return type:

bool

Example:

>>> v = ti.Vector([0, 0, 1])
>>> v.any()
True
cast(self, dtype)#

Cast the matrix elements to a specified data type.

Parameters:

dtype (primitive_types) – data type of the returned matrix.

Returns:

A new matrix with the specified data dtype.

Return type:

taichi.Matrix

Example:

>>> A = ti.Matrix([0, 1, 2], ti.i32)
>>> B = A.cast(ti.f32)
>>> B
[0.0, 1.0, 2.0]
static cols(cols)#

Constructs a Matrix instance by concatenating Vectors/lists column by column.

Parameters:

cols (List) – A list of Vector (1-D Matrix) or a list of list.

Returns:

A matrix.

Return type:

Matrix

Example:

>>> @ti.kernel
>>> def test():
>>>     v1 = ti.Vector([1, 2, 3])
>>>     v2 = ti.Vector([4, 5, 6])
>>>     m = ti.Matrix.cols([v1, v2])
>>>     print(m)
>>>
>>> test()
[[1, 4], [2, 5], [3, 6]]
cross(self, other)#

Performs the cross product with the input vector (1-D Matrix).

Both two vectors must have the same dimension <= 3.

For two 2d vectors (x1, y1) and (x2, y2), the return value is the scalar x1*y2 - x2*y1.

For two 3d vectors v and w, the return value is the 3d vector v x w.

Parameters:

other (Matrix) – The input Vector.

Returns:

The cross product of the two Vectors.

Return type:

Matrix

determinant(a)#

Returns the determinant of this matrix.

Note

The matrix dimension should be less than or equal to 4.

Returns:

The determinant of this matrix.

Return type:

dtype

Raises:

Exception – Determinants of matrices with sizes >= 5 are not supported.

static diag(dim, val)#

Returns a diagonal square matrix with the diagonals filled with val.

Parameters:
  • dim (int) – the dimension of the wanted square matrix.

  • val (TypeVar) – value for the diagonal elements.

Returns:

The wanted diagonal matrix.

Return type:

Matrix

Example:

>>> m = ti.Matrix.diag(3, 1)
[[1, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]
dot(self, other)#

Performs the dot product of two vectors.

To call this method, both multiplicatives must be vectors.

Parameters:

other (Matrix) – The input Vector.

Returns:

The dot product result (scalar) of the two Vectors.

Return type:

DataType

Example:

>>> v1 = ti.Vector([1, 2, 3])
>>> v2 = ti.Vector([3, 4, 5])
>>> v1.dot(v2)
26
element_type(self)#
classmethod field(cls, n, m, dtype, shape=None, order=None, name='', offset=None, needs_grad=False, needs_dual=False, layout=Layout.AOS, ndim=None)#

Construct a data container to hold all elements of the Matrix.

Parameters:
  • n (int) – The desired number of rows of the Matrix.

  • m (int) – The desired number of columns of the Matrix.

  • dtype (DataType, optional) – The desired data type of the Matrix.

  • shape (Union[int, tuple of int], optional) – The desired shape of the Matrix.

  • order (str, optional) – order of the shape laid out in memory.

  • name (string, optional) – The custom name of the field.

  • offset (Union[int, tuple of int], optional) – The coordinate offset of all elements in a field.

  • needs_grad (bool, optional) – Whether the Matrix need grad field (reverse mode autodiff).

  • needs_dual (bool, optional) – Whether the Matrix need dual field (forward mode autodiff).

  • layout (Layout, optional) – The field layout, either Array Of Structure (AOS) or Structure Of Array (SOA).

Returns:

A matrix.

Return type:

Matrix

fill(self, val)#

Fills the matrix with a specified value.

Parameters:

val (Union[int, float]) – Value to fill.

Example:

>>> A = ti.Matrix([0, 1, 2, 3])
>>> A.fill(-1)
>>> A
[-1, -1, -1, -1]
get_shape(self)#
static identity(dt, n)#

Constructs an identity Matrix with shape (n, n).

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The number of rows/columns.

Returns:

An n x n identity matrix.

Return type:

Matrix

inverse(self)#

Returns the inverse of this matrix.

Note

The matrix dimension should be less than or equal to 4.

Returns:

The inverse of a matrix.

Return type:

Matrix

Raises:

Exception – Inversions of matrices with sizes >= 5 are not supported.

max(self)#

Returns the maximum element value.

min(self)#

Returns the minimum element value.

classmethod ndarray(cls, n, m, dtype, shape)#

Defines a Taichi ndarray with matrix elements. This function must be called in Python scope, and after ti.init is called.

Parameters:
  • n (int) – Number of rows of the matrix.

  • m (int) – Number of columns of the matrix.

  • dtype (DataType) – Data type of each value.

  • shape (Union[int, tuple[int]]) – Shape of the ndarray.

Example:

The code below shows how a Taichi ndarray with matrix elements             can be declared and defined::

    >>> x = ti.Matrix.ndarray(4, 5, ti.f32, shape=(16, 8))
norm(self, eps=0)#

Returns the square root of the sum of the absolute squares of its elements.

Parameters:

eps (Number) – a safe-guard value for sqrt, usually 0.

Example:

>>> a = ti.Vector([3, 4])
>>> a.norm()
5
Returns:

The square root of the sum of the absolute squares of its elements.

norm_inv(self, eps=0)#

The inverse of the matrix norm().

Parameters:

eps (float) – a safe-guard value for sqrt, usually 0.

Returns:

The inverse of the matrix/vector norm.

norm_sqr(self)#

Returns the sum of the absolute squares of its elements.

normalized(self, eps=0)#

Normalize a vector, i.e. matrices with the second dimension being equal to one.

The normalization of a vector v is a vector of length 1 and has the same direction with v. It’s equal to v/|v|.

Parameters:

eps (float) – a safe-guard value for sqrt, usually 0.

Example:

>>> a = ti.Vector([3, 4], ti.f32)
>>> a.normalized()
[0.6, 0.8]
static one(dt, n, m=None)#

Constructs a Matrix filled with ones.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with ones.

Return type:

Matrix

outer_product(self, other)#

Performs the outer product with the input Vector (1-D Matrix).

The outer_product of two vectors v = (x1, x2, …, xn), w = (y1, y2, …, yn) is a n times n square matrix, and its (i, j) entry is equal to xi*yj.

Parameters:

other (Matrix) – The input Vector.

Returns:

The outer product of the two Vectors.

Return type:

Matrix

static rotation2d(alpha)#

Returns the matrix representation of the 2D anti-clockwise rotation of angle alpha. The angle alpha is in radians.

Example:

>>> import math
>>> ti.Matrix.rotation2d(math.pi/4)
[[ 0.70710678 -0.70710678]
 [ 0.70710678  0.70710678]]
static rows(rows)#

Constructs a matrix by concatenating a list of vectors/lists row by row. Must be called in Taichi scope.

Parameters:

rows (List) – A list of Vector (1-D Matrix) or a list of list.

Returns:

A matrix.

Return type:

Matrix

Example:

>>> @ti.kernel
>>> def test():
>>>     v1 = ti.Vector([1, 2, 3])
>>>     v2 = ti.Vector([4, 5, 6])
>>>     m = ti.Matrix.rows([v1, v2])
>>>     print(m)
>>>
>>> test()
[[1, 2, 3], [4, 5, 6]]
sum(self)#

Return the sum of all elements.

Example:

>>> m = ti.Matrix([[1, 2], [3, 4]])
>>> m.sum()
10
to_list(self)#

Return this matrix as a 1D list.

This is similar to numpy.ndarray’s flatten and ravel methods, the difference is that this function always returns a new list.

to_numpy(self, keep_dims=False)#

Converts this matrix to a numpy array.

Parameters:

keep_dims (bool, optional) – Whether to keep the dimension after conversion. If set to False, the resulting numpy array will discard the axis of length one.

Returns:

The result numpy array.

Return type:

numpy.ndarray

Example:

>>> A = ti.Matrix([[0], [1], [2], [3]])
>>> A.to_numpy(keep_dims=False)
>>> A
array([0, 1, 2, 3])
trace(self)#

The sum of a matrix diagonal elements.

To call this method the matrix must be square-like.

Returns:

The sum of a matrix diagonal elements.

Example:

>>> m = ti.Matrix([[1, 2], [3, 4]])
>>> m.trace()
5
transpose(self)#

Returns the transpose of a matrix.

Returns:

The transpose of this matrix.

Return type:

Matrix

Example:

>>> A = ti.Matrix([[0, 1], [2, 3]])
>>> A.transpose()
[[0, 2], [1, 3]]
static unit(n, i, dt=None)#

Constructs a n-D vector with the i-th entry being equal to one and the remaining entries are all zeros.

Parameters:
  • n (int) – The length of the vector.

  • i (int) – The index of the entry that will be filled with one.

  • dt (primitive_types, optional) – The desired data type.

Returns:

The returned vector.

Return type:

Matrix

Example:

>>> A = ti.Matrix.unit(3, 1)
>>> A
[0, 1, 0]
static zero(dt, n, m=None)#

Constructs a Matrix filled with zeros.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with zeros.

Return type:

Matrix

class taichi.lang.matrix.MatrixField(_vars, n, m, ndim=2)#

Bases: taichi.lang.field.Field

Taichi matrix field with SNode implementation.

Parameters:
  • vars (List[Expr]) – Field members.

  • n (Int) – Number of rows.

  • m (Int) – Number of columns.

  • ndim (Int) – Number of dimensions; forced reshape if given.

copy_from(self, other)#

Copies all elements from another field.

The shape of the other field needs to be the same as self.

Parameters:

other (Field) – The source field.

fill(self, val)#

Fills this matrix field with specified values.

Parameters:

val (Union[Number, Expr, List, Tuple, Matrix]) – Values to fill, should have consistent dimension consistent with self.

from_numpy(self, arr)#

Copies an numpy.ndarray into this field.

Example:

>>> m = ti.Matrix.field(2, 2, ti.f32, shape=(3, 3))
>>> arr = numpy.ones((3, 3, 2, 2))
>>> m.from_numpy(arr)
from_paddle(self, arr)#

Loads all elements from a paddle tensor.

The shape of the paddle tensor needs to be the same as self.

Parameters:

arr (paddle.Tensor) – The source paddle tensor.

from_torch(self, arr)#

Loads all elements from a torch tensor.

The shape of the torch tensor needs to be the same as self.

Parameters:

arr (torch.tensor) – The source torch tensor.

get_scalar_field(self, *indices)#

Creates a ScalarField using a specific field member.

Parameters:

indices (Tuple[Int]) – Specified indices of the field member.

Returns:

The result ScalarField.

Return type:

ScalarField

parent(self, n=1)#

Gets an ancestor of the representative SNode in the SNode tree.

Parameters:

n (int) – the number of levels going up from the representative SNode.

Returns:

The n-th parent of the representative SNode.

Return type:

SNode

to_numpy(self, keep_dims=False, dtype=None)#

Converts the field instance to a NumPy array.

Parameters:
  • keep_dims (bool, optional) – Whether to keep the dimension after conversion. When keep_dims=True, on an n-D matrix field, the numpy array always has n+2 dims, even for 1x1, 1xn, nx1 matrix fields. When keep_dims=False, the resulting numpy array should skip the matrix dims with size 1. For example, a 4x1 or 1x4 matrix field with 5x6x7 elements results in an array of shape 5x6x7x4.

  • dtype (DataType, optional) – The desired data type of returned numpy array.

Returns:

The result NumPy array.

Return type:

numpy.ndarray

to_paddle(self, place=None, keep_dims=False)#

Converts the field instance to a Paddle tensor.

Parameters:
  • place (paddle.CPUPlace()/CUDAPlace(n), optional) – The desired place of returned tensor.

  • keep_dims (bool, optional) – Whether to keep the dimension after conversion. See to_numpy() for more detailed explanation.

Returns:

The result paddle tensor.

Return type:

paddle.Tensor

to_torch(self, device=None, keep_dims=False)#

Converts the field instance to a PyTorch tensor.

Parameters:
  • device (torch.device, optional) – The desired device of returned tensor.

  • keep_dims (bool, optional) – Whether to keep the dimension after conversion. See to_numpy() for more detailed explanation.

Returns:

The result torch tensor.

Return type:

torch.tensor

class taichi.lang.matrix.MatrixNdarray(n, m, dtype, shape)#

Bases: taichi.lang._ndarray.Ndarray

Taichi ndarray with matrix elements.

Parameters:
  • n (int) – Number of rows of the matrix.

  • m (int) – Number of columns of the matrix.

  • dtype (DataType) – Data type of each value.

  • shape (Union[int, tuple[int]]) – Shape of the ndarray.

Example:

>>> arr = ti.MatrixNdarray(2, 2, ti.f32, shape=(3, 3))
copy_from(self, other)#

Copies all elements from another ndarray.

The shape of the other ndarray needs to be the same as self.

Parameters:

other (Ndarray) – The source ndarray.

fill(self, val)#

Fills ndarray with a specific scalar value.

Parameters:

val (Union[int, float]) – Value to fill.

from_numpy(self, arr)#

Copies the data of a numpy.ndarray into this array.

Example:

>>> m = ti.MatrixNdarray(2, 2, ti.f32, shape=(2, 1), layout=0)
>>> arr = np.ones((2, 1, 2, 2))
>>> m.from_numpy(arr)
get_type(self)#
to_numpy(self)#

Converts this ndarray to a numpy.ndarray.

Example:

>>> arr = ti.MatrixNdarray(2, 2, ti.f32, shape=(2, 1))
>>> arr.to_numpy()
[[[[0. 0.]
   [0. 0.]]]

 [[[0. 0.]
   [0. 0.]]]]
class taichi.lang.matrix.Vector(arr, dt=None, **kwargs)#

Bases: Matrix

The matrix class.

A matrix is a 2-D rectangular array with scalar entries, it’s row-majored, and is aligned continuously. We recommend only use matrix with no more than 32 elements for efficiency considerations.

Note: in taichi a matrix is strictly two-dimensional and only stores scalars.

Parameters:
  • arr (Union[list, tuple, np.ndarray]) – the initial values of a matrix.

  • dt (primitive_types) – the element data type.

  • ndim (int optional) – the number of dimensions of the matrix; forced reshape if given.

Example:

use a 2d list to initialize a matrix

>>> @ti.kernel
>>> def test():
>>>     n = 5
>>>     M = ti.Matrix([[0] * n for _ in range(n)], ti.i32)
>>>     print(M)  # a 5x5 matrix with integer elements

get the number of rows and columns via the `n`, `m` property:

>>> M = ti.Matrix([[0, 1], [2, 3], [4, 5]], ti.i32)
>>> M.n  # number of rows
3
>>> M.m  # number of cols
>>> 2

you can even initialize a matrix with an empty list:

>>> M = ti.Matrix([[], []], ti.i32)
>>> M.n
2
>>> M.m
0
all(self)#

Test whether all element not equal zero.

Returns:

True if all elements are not equal zero, False otherwise.

Return type:

bool

Example:

>>> v = ti.Vector([0, 0, 1])
>>> v.all()
False
any(self)#

Test whether any element not equal zero.

Returns:

True if any element is not equal zero, False otherwise.

Return type:

bool

Example:

>>> v = ti.Vector([0, 0, 1])
>>> v.any()
True
cast(self, dtype)#

Cast the matrix elements to a specified data type.

Parameters:

dtype (primitive_types) – data type of the returned matrix.

Returns:

A new matrix with the specified data dtype.

Return type:

taichi.Matrix

Example:

>>> A = ti.Matrix([0, 1, 2], ti.i32)
>>> B = A.cast(ti.f32)
>>> B
[0.0, 1.0, 2.0]
static cols(cols)#

Constructs a Matrix instance by concatenating Vectors/lists column by column.

Parameters:

cols (List) – A list of Vector (1-D Matrix) or a list of list.

Returns:

A matrix.

Return type:

Matrix

Example:

>>> @ti.kernel
>>> def test():
>>>     v1 = ti.Vector([1, 2, 3])
>>>     v2 = ti.Vector([4, 5, 6])
>>>     m = ti.Matrix.cols([v1, v2])
>>>     print(m)
>>>
>>> test()
[[1, 4], [2, 5], [3, 6]]
cross(self, other)#

Performs the cross product with the input vector (1-D Matrix).

Both two vectors must have the same dimension <= 3.

For two 2d vectors (x1, y1) and (x2, y2), the return value is the scalar x1*y2 - x2*y1.

For two 3d vectors v and w, the return value is the 3d vector v x w.

Parameters:

other (Matrix) – The input Vector.

Returns:

The cross product of the two Vectors.

Return type:

Matrix

determinant(a)#

Returns the determinant of this matrix.

Note

The matrix dimension should be less than or equal to 4.

Returns:

The determinant of this matrix.

Return type:

dtype

Raises:

Exception – Determinants of matrices with sizes >= 5 are not supported.

static diag(dim, val)#

Returns a diagonal square matrix with the diagonals filled with val.

Parameters:
  • dim (int) – the dimension of the wanted square matrix.

  • val (TypeVar) – value for the diagonal elements.

Returns:

The wanted diagonal matrix.

Return type:

Matrix

Example:

>>> m = ti.Matrix.diag(3, 1)
[[1, 0, 0],
 [0, 1, 0],
 [0, 0, 1]]
dot(self, other)#

Performs the dot product of two vectors.

To call this method, both multiplicatives must be vectors.

Parameters:

other (Matrix) – The input Vector.

Returns:

The dot product result (scalar) of the two Vectors.

Return type:

DataType

Example:

>>> v1 = ti.Vector([1, 2, 3])
>>> v2 = ti.Vector([3, 4, 5])
>>> v1.dot(v2)
26
element_type(self)#
classmethod field(cls, n, dtype, *args, **kwargs)#

ti.Vector.field

fill(self, val)#

Fills the matrix with a specified value.

Parameters:

val (Union[int, float]) – Value to fill.

Example:

>>> A = ti.Matrix([0, 1, 2, 3])
>>> A.fill(-1)
>>> A
[-1, -1, -1, -1]
get_shape(self)#
static identity(dt, n)#

Constructs an identity Matrix with shape (n, n).

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The number of rows/columns.

Returns:

An n x n identity matrix.

Return type:

Matrix

inverse(self)#

Returns the inverse of this matrix.

Note

The matrix dimension should be less than or equal to 4.

Returns:

The inverse of a matrix.

Return type:

Matrix

Raises:

Exception – Inversions of matrices with sizes >= 5 are not supported.

max(self)#

Returns the maximum element value.

min(self)#

Returns the minimum element value.

classmethod ndarray(cls, n, dtype, shape)#

Defines a Taichi ndarray with vector elements.

Parameters:
  • n (int) – Size of the vector.

  • dtype (DataType) – Data type of each value.

  • shape (Union[int, tuple[int]]) – Shape of the ndarray.

  • layout (Layout, optional) – Memory layout, AOS by default.

Example

The code below shows how a Taichi ndarray with vector elements can be declared and defined:

>>> x = ti.Vector.ndarray(3, ti.f32, shape=(16, 8))
norm(self, eps=0)#

Returns the square root of the sum of the absolute squares of its elements.

Parameters:

eps (Number) – a safe-guard value for sqrt, usually 0.

Example:

>>> a = ti.Vector([3, 4])
>>> a.norm()
5
Returns:

The square root of the sum of the absolute squares of its elements.

norm_inv(self, eps=0)#

The inverse of the matrix norm().

Parameters:

eps (float) – a safe-guard value for sqrt, usually 0.

Returns:

The inverse of the matrix/vector norm.

norm_sqr(self)#

Returns the sum of the absolute squares of its elements.

normalized(self, eps=0)#

Normalize a vector, i.e. matrices with the second dimension being equal to one.

The normalization of a vector v is a vector of length 1 and has the same direction with v. It’s equal to v/|v|.

Parameters:

eps (float) – a safe-guard value for sqrt, usually 0.

Example:

>>> a = ti.Vector([3, 4], ti.f32)
>>> a.normalized()
[0.6, 0.8]
static one(dt, n, m=None)#

Constructs a Matrix filled with ones.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with ones.

Return type:

Matrix

outer_product(self, other)#

Performs the outer product with the input Vector (1-D Matrix).

The outer_product of two vectors v = (x1, x2, …, xn), w = (y1, y2, …, yn) is a n times n square matrix, and its (i, j) entry is equal to xi*yj.

Parameters:

other (Matrix) – The input Vector.

Returns:

The outer product of the two Vectors.

Return type:

Matrix

static rotation2d(alpha)#

Returns the matrix representation of the 2D anti-clockwise rotation of angle alpha. The angle alpha is in radians.

Example:

>>> import math
>>> ti.Matrix.rotation2d(math.pi/4)
[[ 0.70710678 -0.70710678]
 [ 0.70710678  0.70710678]]
static rows(rows)#

Constructs a matrix by concatenating a list of vectors/lists row by row. Must be called in Taichi scope.

Parameters:

rows (List) – A list of Vector (1-D Matrix) or a list of list.

Returns:

A matrix.

Return type:

Matrix

Example:

>>> @ti.kernel
>>> def test():
>>>     v1 = ti.Vector([1, 2, 3])
>>>     v2 = ti.Vector([4, 5, 6])
>>>     m = ti.Matrix.rows([v1, v2])
>>>     print(m)
>>>
>>> test()
[[1, 2, 3], [4, 5, 6]]
sum(self)#

Return the sum of all elements.

Example:

>>> m = ti.Matrix([[1, 2], [3, 4]])
>>> m.sum()
10
to_list(self)#

Return this matrix as a 1D list.

This is similar to numpy.ndarray’s flatten and ravel methods, the difference is that this function always returns a new list.

to_numpy(self, keep_dims=False)#

Converts this matrix to a numpy array.

Parameters:

keep_dims (bool, optional) – Whether to keep the dimension after conversion. If set to False, the resulting numpy array will discard the axis of length one.

Returns:

The result numpy array.

Return type:

numpy.ndarray

Example:

>>> A = ti.Matrix([[0], [1], [2], [3]])
>>> A.to_numpy(keep_dims=False)
>>> A
array([0, 1, 2, 3])
trace(self)#

The sum of a matrix diagonal elements.

To call this method the matrix must be square-like.

Returns:

The sum of a matrix diagonal elements.

Example:

>>> m = ti.Matrix([[1, 2], [3, 4]])
>>> m.trace()
5
transpose(self)#

Returns the transpose of a matrix.

Returns:

The transpose of this matrix.

Return type:

Matrix

Example:

>>> A = ti.Matrix([[0, 1], [2, 3]])
>>> A.transpose()
[[0, 2], [1, 3]]
static unit(n, i, dt=None)#

Constructs a n-D vector with the i-th entry being equal to one and the remaining entries are all zeros.

Parameters:
  • n (int) – The length of the vector.

  • i (int) – The index of the entry that will be filled with one.

  • dt (primitive_types, optional) – The desired data type.

Returns:

The returned vector.

Return type:

Matrix

Example:

>>> A = ti.Matrix.unit(3, 1)
>>> A
[0, 1, 0]
static zero(dt, n, m=None)#

Constructs a Matrix filled with zeros.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with zeros.

Return type:

Matrix

class taichi.lang.matrix.VectorNdarray(n, dtype, shape)#

Bases: taichi.lang._ndarray.Ndarray

Taichi ndarray with vector elements.

Parameters:
  • n (int) – Size of the vector.

  • dtype (DataType) – Data type of each value.

  • shape (Tuple[int]) – Shape of the ndarray.

  • layout (Layout) – Memory layout.

Example:

>>> a = ti.VectorNdarray(3, ti.f32, (3, 3))
copy_from(self, other)#

Copies all elements from another ndarray.

The shape of the other ndarray needs to be the same as self.

Parameters:

other (Ndarray) – The source ndarray.

fill(self, val)#

Fills ndarray with a specific scalar value.

Parameters:

val (Union[int, float]) – Value to fill.

from_numpy(self, arr)#

Copies the data from a numpy.ndarray into this ndarray.

The shape and data type of arr must match this ndarray.

Example:

>>> import numpy as np
>>> a = ti.VectorNdarray(3, ti.f32, (2, 2), 0)
>>> b = np.ones((2, 2, 3), dtype=np.float32)
>>> a.from_numpy(b)
get_type(self)#
to_numpy(self)#

Converts this vector ndarray to a numpy.ndarray.

Example:

>>> a = ti.VectorNdarray(3, ti.f32, (2, 2))
>>> a.to_numpy()
array([[[0., 0., 0.],
        [0., 0., 0.]],

       [[0., 0., 0.],
        [0., 0., 0.]]], dtype=float32)
Was this helpful?