All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
Matrix< Real > Singleton Reference

A class for storing matrices. More...

#include <kaldi-matrix.h>

Inheritance diagram for Matrix< Real >:
Collaboration diagram for Matrix< Real >:

Public Member Functions

 Matrix ()
 Empty constructor. More...
 
 Matrix (const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
 Basic constructor. More...
 
template<typename OtherReal >
 Matrix (const CuMatrixBase< OtherReal > &cu, MatrixTransposeType trans=kNoTrans)
 Copy constructor from CUDA matrix This is defined in ../cudamatrix/cu-matrix.h. More...
 
void Swap (Matrix< Real > *other)
 Swaps the contents of *this and *other. Shallow swap. More...
 
void Swap (CuMatrix< Real > *mat)
 Defined in ../cudamatrix/cu-matrix.cc. More...
 
 Matrix (const MatrixBase< Real > &M, MatrixTransposeType trans=kNoTrans)
 Constructor from any MatrixBase. More...
 
 Matrix (const Matrix< Real > &M)
 Same as above, but need to avoid default copy constructor. More...
 
template<typename OtherReal >
 Matrix (const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
 Copy constructor: as above, but from another type. More...
 
template<typename OtherReal >
 Matrix (const SpMatrix< OtherReal > &M)
 Copy constructor taking SpMatrix... More...
 
 Matrix (const CompressedMatrix &C)
 Constructor from CompressedMatrix. More...
 
template<typename OtherReal >
 Matrix (const TpMatrix< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
 Copy constructor taking TpMatrix... More...
 
void Read (std::istream &in, bool binary, bool add=false)
 read from stream. More...
 
void RemoveRow (MatrixIndexT i)
 Remove a specified row. More...
 
void Transpose ()
 Transpose the matrix. More...
 
 ~Matrix ()
 Distructor to free matrices. More...
 
void Resize (const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
 Sets matrix to a specified size (zero is OK as long as both r and c are zero). More...
 
Matrix< Real > & operator= (const MatrixBase< Real > &other)
 Assignment operator that takes MatrixBase. More...
 
Matrix< Real > & operator= (const Matrix< Real > &other)
 Assignment operator. Needed for inclusion in std::vector. More...
 
template<typename Real >
 Matrix (const MatrixBase< Real > &M, MatrixTransposeType trans)
 
template<typename Real >
 Matrix (const Matrix< Real > &M)
 
template<typename OtherReal >
 Matrix (const MatrixBase< OtherReal > &M, MatrixTransposeType trans)
 Copy constructor from another type. More...
 
template<class Real >
 Matrix (const CompressedMatrix &M)
 
- Public Member Functions inherited from MatrixBase< Real >
MatrixIndexT NumRows () const
 Returns number of rows (or zero for emtpy matrix). More...
 
MatrixIndexT NumCols () const
 Returns number of columns (or zero for emtpy matrix). More...
 
MatrixIndexT Stride () const
 Stride (distance in memory between each row). Will be >= NumCols. More...
 
size_t SizeInBytes () const
 Returns size in bytes of the data held by the matrix. More...
 
const Real * Data () const
 Gives pointer to raw data (const). More...
 
Real * Data ()
 Gives pointer to raw data (non-const). More...
 
Real * RowData (MatrixIndexT i)
 Returns pointer to data for one row (non-const) More...
 
const Real * RowData (MatrixIndexT i) const
 Returns pointer to data for one row (const) More...
 
Real & operator() (MatrixIndexT r, MatrixIndexT c)
 Indexing operator, non-const (only checks sizes if compiled with -DKALDI_PARANOID) More...
 
Real & Index (MatrixIndexT r, MatrixIndexT c)
 Indexing operator, provided for ease of debugging (gdb doesn't work with parenthesis operator). More...
 
const Real operator() (MatrixIndexT r, MatrixIndexT c) const
 Indexing operator, const (only checks sizes if compiled with -DKALDI_PARANOID) More...
 
void SetZero ()
 Sets matrix to zero. More...
 
void Set (Real)
 Sets all elements to a specific value. More...
 
void SetUnit ()
 Sets to zero, except ones along diagonal [for non-square matrices too]. More...
 
void SetRandn ()
 Sets to random values of a normal distribution. More...
 
void SetRandUniform ()
 Sets to numbers uniformly distributed on (0, 1) More...
 
template<typename OtherReal >
void CopyFromMat (const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
 Copy given matrix. (no resize is done). More...
 
void CopyFromMat (const CompressedMatrix &M)
 Copy from compressed matrix. More...
 
template<typename OtherReal >
void CopyFromSp (const SpMatrix< OtherReal > &M)
 Copy given spmatrix. (no resize is done). More...
 
template<typename OtherReal >
void CopyFromTp (const TpMatrix< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
 Copy given tpmatrix. (no resize is done). More...
 
template<typename OtherReal >
void CopyFromMat (const CuMatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
 Copy from CUDA matrix. Implemented in ../cudamatrix/cu-matrix.h. More...
 
void CopyRowsFromVec (const VectorBase< Real > &v)
 This function has two modes of operation. More...
 
void CopyRowsFromVec (const CuVectorBase< Real > &v)
 This version of CopyRowsFromVec is implemented in ../cudamatrix/cu-vector.cc. More...
 
template<typename OtherReal >
void CopyRowsFromVec (const VectorBase< OtherReal > &v)
 
void CopyColsFromVec (const VectorBase< Real > &v)
 Copies vector into matrix, column-by-column. More...
 
void CopyColFromVec (const VectorBase< Real > &v, const MatrixIndexT col)
 Copy vector into specific column of matrix. More...
 
void CopyRowFromVec (const VectorBase< Real > &v, const MatrixIndexT row)
 Copy vector into specific row of matrix. More...
 
void CopyDiagFromVec (const VectorBase< Real > &v)
 Copy vector into diagonal of matrix. More...
 
const SubVector< Real > Row (MatrixIndexT i) const
 Return specific row of matrix [const]. More...
 
SubVector< Real > Row (MatrixIndexT i)
 Return specific row of matrix. More...
 
SubMatrix< Real > Range (const MatrixIndexT row_offset, const MatrixIndexT num_rows, const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
 Return a sub-part of matrix. More...
 
SubMatrix< Real > RowRange (const MatrixIndexT row_offset, const MatrixIndexT num_rows) const
 
SubMatrix< Real > ColRange (const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
 
Real Sum () const
 Returns sum of all elements in matrix. More...
 
Real Trace (bool check_square=true) const
 Returns trace of matrix. More...
 
Real Max () const
 Returns maximum element of matrix. More...
 
Real Min () const
 Returns minimum element of matrix. More...
 
void MulElements (const MatrixBase< Real > &A)
 Element by element multiplication with a given matrix. More...
 
void DivElements (const MatrixBase< Real > &A)
 Divide each element by the corresponding element of a given matrix. More...
 
void Scale (Real alpha)
 Multiply each element with a scalar value. More...
 
void Max (const MatrixBase< Real > &A)
 Set, element-by-element, *this = max(*this, A) More...
 
void Min (const MatrixBase< Real > &A)
 Set, element-by-element, *this = min(*this, A) More...
 
void MulColsVec (const VectorBase< Real > &scale)
 Equivalent to (*this) = (*this) * diag(scale). More...
 
void MulRowsVec (const VectorBase< Real > &scale)
 Equivalent to (*this) = diag(scale) * (*this). More...
 
void MulRowsGroupMat (const MatrixBase< Real > &src)
 Divide each row into src.NumCols() equal groups, and then scale i'th row's j'th group of elements by src(i, j). More...
 
Real LogDet (Real *det_sign=NULL) const
 Returns logdet of matrix. More...
 
void Invert (Real *log_det=NULL, Real *det_sign=NULL, bool inverse_needed=true)
 matrix inverse. More...
 
void InvertDouble (Real *LogDet=NULL, Real *det_sign=NULL, bool inverse_needed=true)
 matrix inverse [double]. More...
 
void InvertElements ()
 Inverts all the elements of the matrix. More...
 
void Transpose ()
 Transpose the matrix. More...
 
void CopyCols (const MatrixBase< Real > &src, const MatrixIndexT *indices)
 Copies column r from column indices[r] of src. More...
 
void CopyRows (const MatrixBase< Real > &src, const MatrixIndexT *indices)
 Copies row r from row indices[r] of src (does nothing As a special case, if indexes[i] == -1, sets row i to zero. More...
 
void AddCols (const MatrixBase< Real > &src, const MatrixIndexT *indices)
 Add column indices[r] of src to column r. More...
 
void CopyRows (const Real *const *src)
 Copies row r of this matrix from an array of floats at the location given by src[r]. More...
 
void CopyToRows (Real *const *dst) const
 Copies row r of this matrix to the array of floats at the location given by dst[r]. More...
 
void AddRows (Real alpha, const MatrixBase< Real > &src, const MatrixIndexT *indexes)
 Does for each row r, this.Row(r) += alpha * src.row(indexes[r]). More...
 
void AddRows (Real alpha, const Real *const *src)
 Does for each row r, this.Row(r) += alpha * src[r], treating src[r] as the beginning of a region of memory representing a vector of floats, of the same length as this.NumCols(). More...
 
void AddToRows (Real alpha, Real *const *dst) const
 For each row r of this matrix, adds it (times alpha) to the array of floats at the location given by dst[r]. More...
 
void AddToRows (Real alpha, const MatrixIndexT *indexes, MatrixBase< Real > *dst) const
 For each row i of *this, adds this->Row(i) to dst->Row(indexes(i)) if indexes(i) >= 0, else do nothing. More...
 
void ApplyFloor (Real floor_val)
 Applies floor to all matrix elements. More...
 
void ApplyCeiling (Real ceiling_val)
 Applies floor to all matrix elements. More...
 
void ApplyLog ()
 Calculates log of all the matrix elemnts. More...
 
void ApplyExp ()
 Exponentiate each of the elements. More...
 
void ApplyExpSpecial ()
 For each element x of the matrix, set it to (x < 0 ? exp(x) : x + 1). More...
 
void ApplyPow (Real power)
 Applies power to all matrix elements. More...
 
void ApplyPowAbs (Real power, bool include_sign=false)
 Apply power to the absolute value of each element. More...
 
void ApplyHeaviside ()
 Applies the Heaviside step function (x > 0 ? 1 : 0) to all matrix elements Note: in general you can make different choices for x = 0, but for now please leave it as it (i.e. More...
 
void Eig (MatrixBase< Real > *P, VectorBase< Real > *eigs_real, VectorBase< Real > *eigs_imag) const
 Eigenvalue Decomposition of a square NxN matrix into the form (*this) = P D P^{-1}. More...
 
bool Power (Real pow)
 The Power method attempts to take the matrix to a power using a method that works in general for fractional and negative powers. More...
 
void DestructiveSvd (VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt)
 Singular value decomposition Major limitations: For nonsquare matrices, we assume m>=n (NumRows >= NumCols), and we return the "skinny" Svd, i.e. More...
 
void Svd (VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt) const
 Compute SVD (*this) = U diag(s) Vt. More...
 
void Svd (VectorBase< Real > *s) const
 Compute SVD but only retain the singular values. More...
 
Real MinSingularValue () const
 Returns smallest singular value. More...
 
void TestUninitialized () const
 
Real Cond () const
 Returns condition number by computing Svd. More...
 
bool IsSymmetric (Real cutoff=1.0e-05) const
 Returns true if matrix is Symmetric. More...
 
bool IsDiagonal (Real cutoff=1.0e-05) const
 Returns true if matrix is Diagonal. More...
 
bool IsUnit (Real cutoff=1.0e-05) const
 Returns true if the matrix is all zeros, except for ones on diagonal. More...
 
bool IsZero (Real cutoff=1.0e-05) const
 Returns true if matrix is all zeros. More...
 
Real FrobeniusNorm () const
 Frobenius norm, which is the sqrt of sum of square elements. More...
 
bool ApproxEqual (const MatrixBase< Real > &other, float tol=0.01) const
 Returns true if ((*this)-other).FrobeniusNorm() <= tol * (*this).FrobeniusNorm(). More...
 
bool Equal (const MatrixBase< Real > &other) const
 Tests for exact equality. It's usually preferable to use ApproxEqual. More...
 
Real LargestAbsElem () const
 largest absolute value. More...
 
Real LogSumExp (Real prune=-1.0) const
 Returns log(sum(exp())) without exp overflow If prune > 0.0, it uses a pruning beam, discarding terms less than (max - prune). More...
 
Real ApplySoftMax ()
 Apply soft-max to the collection of all elements of the matrix and return normalizer (log sum of exponentials). More...
 
void Sigmoid (const MatrixBase< Real > &src)
 Set each element to the sigmoid of the corresponding element of "src". More...
 
void Heaviside (const MatrixBase< Real > &src)
 Sets each element to the Heaviside step function (x > 0 ? 1 : 0) of the corresponding element in "src". More...
 
void SoftHinge (const MatrixBase< Real > &src)
 Set each element to y = log(1 + exp(x)) More...
 
void GroupPnorm (const MatrixBase< Real > &src, Real power)
 Apply the function y(i) = (sum_{j = i*G}^{(i+1)*G-1} x_j^(power))^(1 / p). More...
 
void GroupPnormDeriv (const MatrixBase< Real > &input, const MatrixBase< Real > &output, Real power)
 Calculate derivatives for the GroupPnorm function above... More...
 
void GroupMax (const MatrixBase< Real > &src)
 Apply the function y(i) = (max_{j = i*G}^{(i+1)*G-1} x_j Requires src.NumRows() == this->NumRows() and src.NumCols() % this->NumCols() == 0. More...
 
void GroupMaxDeriv (const MatrixBase< Real > &input, const MatrixBase< Real > &output)
 Calculate derivatives for the GroupMax function above, where "input" is the input to the GroupMax function above (i.e. More...
 
void Tanh (const MatrixBase< Real > &src)
 Set each element to the tanh of the corresponding element of "src". More...
 
void DiffSigmoid (const MatrixBase< Real > &value, const MatrixBase< Real > &diff)
 
void DiffTanh (const MatrixBase< Real > &value, const MatrixBase< Real > &diff)
 
void SymPosSemiDefEig (VectorBase< Real > *s, MatrixBase< Real > *P, Real check_thresh=0.001)
 Uses Svd to compute the eigenvalue decomposition of a symmetric positive semi-definite matrix: (*this) = rP * diag(rS) * rP^T, with rP an orthogonal matrix so rP^{-1} = rP^T. More...
 
void Add (const Real alpha)
 Add a scalar to each element. More...
 
void AddToDiag (const Real alpha)
 Add a scalar to each diagonal element. More...
 
template<typename OtherReal >
void AddVecVec (const Real alpha, const VectorBase< OtherReal > &a, const VectorBase< OtherReal > &b)
 *this += alpha * a * b^T More...
 
template<typename OtherReal >
void AddVecToRows (const Real alpha, const VectorBase< OtherReal > &v)
 [each row of *this] += alpha * v More...
 
template<typename OtherReal >
void AddVecToCols (const Real alpha, const VectorBase< OtherReal > &v)
 [each col of *this] += alpha * v More...
 
void AddMat (const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transA=kNoTrans)
 *this += alpha * M [or M^T] More...
 
void AddSmat (Real alpha, const SparseMatrix< Real > &A, MatrixTransposeType trans=kNoTrans)
 *this += alpha * A [or A^T]. More...
 
void AddSmatMat (Real alpha, const SparseMatrix< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, Real beta)
 (*this) = alpha * op(A) * B + beta * (*this), where A is sparse. More...
 
void AddMatSmat (Real alpha, const MatrixBase< Real > &A, const SparseMatrix< Real > &B, MatrixTransposeType transB, Real beta)
 (*this) = alpha * A * op(B) + beta * (*this), where B is sparse and op(B) is either B or trans(B) depending on the 'transB' argument. More...
 
void SymAddMat2 (const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transA, Real beta)
 *this = beta * *this + alpha * M M^T, for symmetric matrices. More...
 
void AddDiagVecMat (const Real alpha, const VectorBase< Real > &v, const MatrixBase< Real > &M, MatrixTransposeType transM, Real beta=1.0)
 *this = beta * *this + alpha * diag(v) * M [or M^T]. More...
 
void AddMatDiagVec (const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transM, VectorBase< Real > &v, Real beta=1.0)
 *this = beta * *this + alpha * M [or M^T] * diag(v) The same as adding M but scaling each column M_j by v(j). More...
 
void AddMatMatElements (const Real alpha, const MatrixBase< Real > &A, const MatrixBase< Real > &B, const Real beta)
 *this = beta * *this + alpha * A .* B (.* element by element multiplication) More...
 
template<typename OtherReal >
void AddSp (const Real alpha, const SpMatrix< OtherReal > &S)
 *this += alpha * S More...
 
void AddMatMat (const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
 
void SetMatMatDivMat (const MatrixBase< Real > &A, const MatrixBase< Real > &B, const MatrixBase< Real > &C)
 *this = a * b / c (by element; when c = 0, *this = a) More...
 
void AddMatSmat (const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
 A version of AddMatMat specialized for when the second argument contains a lot of zeroes. More...
 
void AddSmatMat (const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
 A version of AddMatMat specialized for when the first argument contains a lot of zeroes. More...
 
void AddMatMatMat (const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const MatrixBase< Real > &C, MatrixTransposeType transC, const Real beta)
 this <– beta*this + alpha*A*B*C. More...
 
void AddSpMat (const Real alpha, const SpMatrix< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
 this <– beta*this + alpha*SpA*B. More...
 
void AddTpMat (const Real alpha, const TpMatrix< Real > &A, MatrixTransposeType transA, const MatrixBase< Real > &B, MatrixTransposeType transB, const Real beta)
 this <– beta*this + alpha*A*B. More...
 
void AddMatSp (const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const SpMatrix< Real > &B, const Real beta)
 this <– beta*this + alpha*A*B. More...
 
void AddSpMatSp (const Real alpha, const SpMatrix< Real > &A, const MatrixBase< Real > &B, MatrixTransposeType transB, const SpMatrix< Real > &C, const Real beta)
 this <– beta*this + alpha*A*B*C. More...
 
void AddMatTp (const Real alpha, const MatrixBase< Real > &A, MatrixTransposeType transA, const TpMatrix< Real > &B, MatrixTransposeType transB, const Real beta)
 this <– beta*this + alpha*A*B. More...
 
void AddTpTp (const Real alpha, const TpMatrix< Real > &A, MatrixTransposeType transA, const TpMatrix< Real > &B, MatrixTransposeType transB, const Real beta)
 this <– beta*this + alpha*A*B. More...
 
void AddSpSp (const Real alpha, const SpMatrix< Real > &A, const SpMatrix< Real > &B, const Real beta)
 this <– beta*this + alpha*A*B. More...
 
void CopyLowerToUpper ()
 Copy lower triangle to upper triangle (symmetrize) More...
 
void CopyUpperToLower ()
 Copy upper triangle to lower triangle (symmetrize) More...
 
void OrthogonalizeRows ()
 This function orthogonalizes the rows of a matrix using the Gram-Schmidt process. More...
 
void Read (std::istream &in, bool binary, bool add=false)
 stream read. More...
 
void Write (std::ostream &out, bool binary) const
 write to stream. More...
 
void LapackGesvd (VectorBase< Real > *s, MatrixBase< Real > *U, MatrixBase< Real > *Vt)
 
template<>
void AddVecVec (const float alpha, const VectorBase< float > &ra, const VectorBase< float > &rb)
 
template<>
void AddVecVec (const double alpha, const VectorBase< double > &ra, const VectorBase< double > &rb)
 
template<typename OtherReal >
void AddSp (const Real alpha, const SpMatrix< OtherReal > &S)
 
template<typename OtherReal >
void CopyFromMat (const MatrixBase< OtherReal > &M, MatrixTransposeType Trans)
 
template<typename OtherReal >
void CopyFromSp (const SpMatrix< OtherReal > &M)
 
template<typename OtherReal >
void CopyFromTp (const TpMatrix< OtherReal > &M, MatrixTransposeType Trans)
 
template<typename Real >
void CopyRowsFromVec (const VectorBase< Real > &rv)
 
template<typename OtherReal >
void CopyRowsFromVec (const VectorBase< OtherReal > &rv)
 
template<class Real >
void CopyFromMat (const CompressedMatrix &mat)
 
template<typename OtherReal >
void AddVecToRows (const Real alpha, const VectorBase< OtherReal > &v)
 
template<typename OtherReal >
void AddVecToCols (const Real alpha, const VectorBase< OtherReal > &v)
 

Private Member Functions

void Destroy ()
 Deallocates memory and sets to empty matrix (dimension 0, 0). More...
 
void Init (const MatrixIndexT r, const MatrixIndexT c, const MatrixStrideType stride_type)
 Init assumes the current class contents are invalid (i.e. More...
 

Additional Inherited Members

- Protected Member Functions inherited from MatrixBase< Real >
 MatrixBase (Real *data, MatrixIndexT cols, MatrixIndexT rows, MatrixIndexT stride)
 Initializer, callable only from child. More...
 
 MatrixBase ()
 Initializer, callable only from child. More...
 
 ~MatrixBase ()
 
Real * Data_workaround () const
 A workaround that allows SubMatrix to get a pointer to non-const data for const Matrix. More...
 
- Protected Attributes inherited from MatrixBase< Real >
Real * data_
 data memory area More...
 
MatrixIndexT num_cols_
 these atributes store the real matrix size as it is stored in memory including memalignment More...
 
MatrixIndexT num_rows_
 < Number of columns More...
 
MatrixIndexT stride_
 < Number of rows More...
 

Detailed Description

template<typename Real>
singleton kaldi::Matrix< Real >

A class for storing matrices.

Definition at line 777 of file kaldi-matrix.h.

Constructor & Destructor Documentation

Matrix ( )

Empty constructor.

Definition at line 29 of file kaldi-matrix-inl.h.

29 : MatrixBase<Real>(NULL, 0, 0, 0) { }
Matrix ( const MatrixIndexT  r,
const MatrixIndexT  c,
MatrixResizeType  resize_type = kSetZero,
MatrixStrideType  stride_type = kDefaultStride 
)
inline

Basic constructor.

Definition at line 784 of file kaldi-matrix.h.

786  :
787  MatrixBase<Real>() { Resize(r, c, resize_type, stride_type); }
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
Matrix ( const CuMatrixBase< OtherReal > &  cu,
MatrixTransposeType  trans = kNoTrans 
)
explicit

Copy constructor from CUDA matrix This is defined in ../cudamatrix/cu-matrix.h.

Definition at line 909 of file cu-matrix.h.

References kaldi::kDefaultStride, and kaldi::kNoTrans.

910  {
911  if (trans == kNoTrans) Init(M.NumRows(), M.NumCols(), kDefaultStride);
912  else Init(M.NumCols(), M.NumRows(), kDefaultStride);
913  M.CopyToMat(this, trans);
914 }
void Init(const MatrixIndexT r, const MatrixIndexT c, const MatrixStrideType stride_type)
Init assumes the current class contents are invalid (i.e.
Matrix ( const MatrixBase< Real > &  M,
MatrixTransposeType  trans = kNoTrans 
)
explicit

Constructor from any MatrixBase.

Can also copy with transpose. Allocates new memory.

Matrix ( const Matrix< Real > &  M)

Same as above, but need to avoid default copy constructor.

Matrix ( const MatrixBase< OtherReal > &  M,
MatrixTransposeType  trans = kNoTrans 
)
explicit

Copy constructor: as above, but from another type.

Matrix ( const SpMatrix< OtherReal > &  M)
inlineexplicit

Copy constructor taking SpMatrix...

It is symmetric, so no option for transpose, and NumRows == Cols

Definition at line 818 of file kaldi-matrix.h.

818  : MatrixBase<Real>() {
819  Resize(M.NumRows(), M.NumRows(), kUndefined);
820  this->CopyFromSp(M);
821  }
void CopyFromSp(const SpMatrix< OtherReal > &M)
Copy given spmatrix. (no resize is done).
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
Matrix ( const CompressedMatrix< Real > &  C)
explicit

Constructor from CompressedMatrix.

Matrix ( const TpMatrix< OtherReal > &  M,
MatrixTransposeType  trans = kNoTrans 
)
inlineexplicit

Copy constructor taking TpMatrix...

Definition at line 828 of file kaldi-matrix.h.

829  : MatrixBase<Real>() {
830  if (trans == kNoTrans) {
831  Resize(M.NumRows(), M.NumCols(), kUndefined);
832  this->CopyFromTp(M);
833  } else {
834  Resize(M.NumCols(), M.NumRows(), kUndefined);
835  this->CopyFromTp(M, kTrans);
836  }
837  }
void CopyFromTp(const TpMatrix< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given tpmatrix. (no resize is done).
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
~Matrix ( )
inline

Distructor to free matrices.

Definition at line 851 of file kaldi-matrix.h.

851 { Destroy(); }
void Destroy()
Deallocates memory and sets to empty matrix (dimension 0, 0).
Matrix ( const MatrixBase< Real > &  M,
MatrixTransposeType  trans 
)

Definition at line 739 of file kaldi-matrix.cc.

References MatrixBase< Real >::CopyFromMat(), kaldi::kNoTrans, kaldi::kTrans, MatrixBase< Real >::num_cols_, MatrixBase< Real >::num_rows_, and Matrix< Real >::Resize().

741  : MatrixBase<Real>() {
742  if (trans == kNoTrans) {
743  Resize(M.num_rows_, M.num_cols_);
744  this->CopyFromMat(M);
745  } else {
746  Resize(M.num_cols_, M.num_rows_);
747  this->CopyFromMat(M, kTrans);
748  }
749 }
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
Matrix ( const Matrix< Real > &  M)

Definition at line 753 of file kaldi-matrix.cc.

References MatrixBase< Real >::CopyFromMat(), MatrixBase< Real >::num_cols_, MatrixBase< Real >::num_rows_, and Matrix< Real >::Resize().

753  :
754  MatrixBase<Real>() {
755  Resize(M.num_rows_, M.num_cols_);
756  this->CopyFromMat(M);
757 }
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
Matrix ( const MatrixBase< OtherReal > &  M,
MatrixTransposeType  trans 
)

Copy constructor from another type.

Definition at line 762 of file kaldi-matrix.cc.

References MatrixBase< Real >::CopyFromMat(), kaldi::kNoTrans, kaldi::kTrans, MatrixBase< Real >::NumCols(), MatrixBase< Real >::NumRows(), and Matrix< Real >::Resize().

763  : MatrixBase<Real>() {
764  if (trans == kNoTrans) {
765  Resize(M.NumRows(), M.NumCols());
766  this->CopyFromMat(M);
767  } else {
768  Resize(M.NumCols(), M.NumRows());
769  this->CopyFromMat(M, kTrans);
770  }
771 }
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
Matrix ( const CompressedMatrix< Real > &  M)

Definition at line 2061 of file kaldi-matrix.cc.

References CompressedMatrix::CopyToMat(), kaldi::kUndefined, CompressedMatrix::NumCols(), CompressedMatrix::NumRows(), and Matrix< Real >::Resize().

2061  : MatrixBase<Real>() {
2062  Resize(M.NumRows(), M.NumCols(), kUndefined);
2063  M.CopyToMat(this);
2064 }
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

Member Function Documentation

void Destroy ( )
private

Deallocates memory and sets to empty matrix (dimension 0, 0).

Definition at line 1127 of file kaldi-matrix.cc.

References KALDI_MEMALIGN_FREE.

Referenced by Matrix< BaseFloat >::~Matrix().

1127  {
1128  // we need to free the data block if it was defined
1129  if (NULL != MatrixBase<Real>::data_)
1131  MatrixBase<Real>::data_ = NULL;
1132  MatrixBase<Real>::num_rows_ = MatrixBase<Real>::num_cols_
1133  = MatrixBase<Real>::stride_ = 0;
1134 }
uint64 data_
#define KALDI_MEMALIGN_FREE(x)
Definition: kaldi-utils.h:60
void Init ( const MatrixIndexT  r,
const MatrixIndexT  c,
const MatrixStrideType  stride_type 
)
inlineprivate

Init assumes the current class contents are invalid (i.e.

junk or have already been freed), and it sets the matrix to newly allocated memory with the specified number of rows and columns. r == c == 0 is acceptable. The data memory contents will be undefined.

Definition at line 782 of file kaldi-matrix.cc.

References data_, KALDI_ASSERT, KALDI_MEMALIGN, and kaldi::kDefaultStride.

784  {
785  if (rows * cols == 0) {
786  KALDI_ASSERT(rows == 0 && cols == 0);
787  this->num_rows_ = 0;
788  this->num_cols_ = 0;
789  this->stride_ = 0;
790  this->data_ = NULL;
791  return;
792  }
793  KALDI_ASSERT(rows > 0 && cols > 0);
794  MatrixIndexT skip, stride;
795  size_t size;
796  void *data; // aligned memory block
797  void *temp; // memory block to be really freed
798 
799  // compute the size of skip and real cols
800  skip = ((16 / sizeof(Real)) - cols % (16 / sizeof(Real)))
801  % (16 / sizeof(Real));
802  stride = cols + skip;
803  size = static_cast<size_t>(rows) * static_cast<size_t>(stride)
804  * sizeof(Real);
805 
806  // allocate the memory and set the right dimensions and parameters
807  if (NULL != (data = KALDI_MEMALIGN(16, size, &temp))) {
808  MatrixBase<Real>::data_ = static_cast<Real *> (data);
809  MatrixBase<Real>::num_rows_ = rows;
810  MatrixBase<Real>::num_cols_ = cols;
811  MatrixBase<Real>::stride_ = (stride_type == kDefaultStride ? stride : cols);
812  } else {
813  throw std::bad_alloc();
814  }
815 }
MatrixIndexT stride_
< Number of rows
Definition: kaldi-matrix.h:770
Real * data_
data memory area
Definition: kaldi-matrix.h:762
uint64 data_
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:767
#define KALDI_MEMALIGN(align, size, pp_orig)
Definition: kaldi-utils.h:58
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:766
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:169
Matrix<Real>& operator= ( const MatrixBase< Real > &  other)
inline

Assignment operator that takes MatrixBase.

Definition at line 871 of file kaldi-matrix.h.

871  {
872  if (MatrixBase<Real>::NumRows() != other.NumRows() ||
873  MatrixBase<Real>::NumCols() != other.NumCols())
874  Resize(other.NumRows(), other.NumCols(), kUndefined);
876  return *this;
877  }
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
MatrixIndexT NumCols() const
Returns number of columns (or zero for emtpy matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
Matrix<Real>& operator= ( const Matrix< Real > &  other)
inline

Assignment operator. Needed for inclusion in std::vector.

Definition at line 880 of file kaldi-matrix.h.

880  {
881  if (MatrixBase<Real>::NumRows() != other.NumRows() ||
882  MatrixBase<Real>::NumCols() != other.NumCols())
883  Resize(other.NumRows(), other.NumCols(), kUndefined);
885  return *this;
886  }
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
MatrixIndexT NumCols() const
Returns number of columns (or zero for emtpy matrix).
Definition: kaldi-matrix.h:64
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
void Read ( std::istream &  in,
bool  binary,
bool  add = false 
)

read from stream.

Definition at line 1449 of file kaldi-matrix.cc.

References CompressedMatrix::CopyToMat(), rnnlm::i, rnnlm::j, KALDI_ERR, KALDI_STRCASECMP, KALDI_WARN, MatrixBase< Real >::num_cols_, MatrixBase< Real >::num_rows_, MatrixBase< Real >::NumCols(), CompressedMatrix::NumCols(), MatrixBase< Real >::NumRows(), CompressedMatrix::NumRows(), kaldi::Peek(), CompressedMatrix::Read(), Matrix< Real >::Read(), kaldi::ReadBasicType(), and kaldi::ReadToken().

Referenced by main(), kaldi::operator>>(), AffineXformStats::Read(), CompressedAffineXformStats::Read(), LogisticRegression::Read(), AccumFullGmm::Read(), LdaEstimate::Read(), Sgmm2FmllrGlobalParams::Read(), GaussClusterable::Read(), FmpeStats::Read(), AccumDiagGmm::Read(), MleAmSgmm2Accs::Read(), FullGmm::Read(), Plda::Read(), CompressedMatrix::Read(), DiagGmm::Read(), DiscriminativeNnetExample::Read(), Fmpe::Read(), AmSgmm2::Read(), IvectorExtractor::Read(), OnlineCmvnState::Read(), GeneralMatrix::Read(), IvectorExtractorStats::Read(), MatrixBase< Real >::Read(), CuMatrix< Real >::Read(), Matrix< Real >::Read(), KlHmm::ReadData(), kaldi::ReadKaldiObject(), kaldi::TypeThreeUsage(), kaldi::UnitTestCompressedMatrix(), kaldi::UnitTestComputeGPE(), UnitTestEndless1(), UnitTestEndless2(), kaldi::UnitTestIo(), kaldi::UnitTestIoCross(), UnitTestMono22K(), and UnitTestStereo8K().

1449  {
1450  if (add) {
1451  Matrix<Real> tmp;
1452  tmp.Read(is, binary, false); // read without adding.
1453  if (this->num_rows_ == 0) this->Resize(tmp.num_rows_, tmp.num_cols_);
1454  else {
1455  if (this->num_rows_ != tmp.num_rows_ || this->num_cols_ != tmp.num_cols_) {
1456  if (tmp.num_rows_ == 0) return; // do nothing in this case.
1457  else KALDI_ERR << "Matrix::Read, size mismatch "
1458  << this->num_rows_ << ", " << this->num_cols_
1459  << " vs. " << tmp.num_rows_ << ", " << tmp.num_cols_;
1460  }
1461  }
1462  this->AddMat(1.0, tmp);
1463  return;
1464  }
1465 
1466  // now assume add == false.
1467  MatrixIndexT pos_at_start = is.tellg();
1468  std::ostringstream specific_error;
1469 
1470  if (binary) { // Read in binary mode.
1471  int peekval = Peek(is, binary);
1472  if (peekval == 'C') {
1473  // This code enable us to read CompressedMatrix as a regular matrix.
1474  CompressedMatrix compressed_mat;
1475  compressed_mat.Read(is, binary); // at this point, add == false.
1476  this->Resize(compressed_mat.NumRows(), compressed_mat.NumCols());
1477  compressed_mat.CopyToMat(this);
1478  return;
1479  }
1480  const char *my_token = (sizeof(Real) == 4 ? "FM" : "DM");
1481  char other_token_start = (sizeof(Real) == 4 ? 'D' : 'F');
1482  if (peekval == other_token_start) { // need to instantiate the other type to read it.
1483  typedef typename OtherReal<Real>::Real OtherType; // if Real == float, OtherType == double, and vice versa.
1484  Matrix<OtherType> other(this->num_rows_, this->num_cols_);
1485  other.Read(is, binary, false); // add is false at this point anyway.
1486  this->Resize(other.NumRows(), other.NumCols());
1487  this->CopyFromMat(other);
1488  return;
1489  }
1490  std::string token;
1491  ReadToken(is, binary, &token);
1492  if (token != my_token) {
1493  if (token.length() > 20) token = token.substr(0, 17) + "...";
1494  specific_error << ": Expected token " << my_token << ", got " << token;
1495  goto bad;
1496  }
1497  int32 rows, cols;
1498  ReadBasicType(is, binary, &rows); // throws on error.
1499  ReadBasicType(is, binary, &cols); // throws on error.
1500  if ((MatrixIndexT)rows != this->num_rows_ || (MatrixIndexT)cols != this->num_cols_) {
1501  this->Resize(rows, cols);
1502  }
1503  if (this->Stride() == this->NumCols() && rows*cols!=0) {
1504  is.read(reinterpret_cast<char*>(this->Data()),
1505  sizeof(Real)*rows*cols);
1506  if (is.fail()) goto bad;
1507  } else {
1508  for (MatrixIndexT i = 0; i < (MatrixIndexT)rows; i++) {
1509  is.read(reinterpret_cast<char*>(this->RowData(i)), sizeof(Real)*cols);
1510  if (is.fail()) goto bad;
1511  }
1512  }
1513  if (is.eof()) return;
1514  if (is.fail()) goto bad;
1515  return;
1516  } else { // Text mode.
1517  std::string str;
1518  is >> str; // get a token
1519  if (is.fail()) { specific_error << ": Expected \"[\", got EOF"; goto bad; }
1520  // if ((str.compare("DM") == 0) || (str.compare("FM") == 0)) { // Back compatibility.
1521  // is >> str; // get #rows
1522  // is >> str; // get #cols
1523  // is >> str; // get "["
1524  // }
1525  if (str == "[]") { Resize(0, 0); return; } // Be tolerant of variants.
1526  else if (str != "[") {
1527  if (str.length() > 20) str = str.substr(0, 17) + "...";
1528  specific_error << ": Expected \"[\", got \"" << str << '"';
1529  goto bad;
1530  }
1531  // At this point, we have read "[".
1532  std::vector<std::vector<Real>* > data;
1533  std::vector<Real> *cur_row = new std::vector<Real>;
1534  while (1) {
1535  int i = is.peek();
1536  if (i == -1) { specific_error << "Got EOF while reading matrix data"; goto cleanup; }
1537  else if (static_cast<char>(i) == ']') { // Finished reading matrix.
1538  is.get(); // eat the "]".
1539  i = is.peek();
1540  if (static_cast<char>(i) == '\r') {
1541  is.get();
1542  is.get(); // get \r\n (must eat what we wrote)
1543  } else if (static_cast<char>(i) == '\n') { is.get(); } // get \n (must eat what we wrote)
1544  if (is.fail()) {
1545  KALDI_WARN << "After end of matrix data, read error.";
1546  // we got the data we needed, so just warn for this error.
1547  }
1548  // Now process the data.
1549  if (!cur_row->empty()) data.push_back(cur_row);
1550  else delete(cur_row);
1551  cur_row = NULL;
1552  if (data.empty()) { this->Resize(0, 0); return; }
1553  else {
1554  int32 num_rows = data.size(), num_cols = data[0]->size();
1555  this->Resize(num_rows, num_cols);
1556  for (int32 i = 0; i < num_rows; i++) {
1557  if (static_cast<int32>(data[i]->size()) != num_cols) {
1558  specific_error << "Matrix has inconsistent #cols: " << num_cols
1559  << " vs." << data[i]->size() << " (processing row"
1560  << i << ")";
1561  goto cleanup;
1562  }
1563  for (int32 j = 0; j < num_cols; j++)
1564  (*this)(i, j) = (*(data[i]))[j];
1565  delete data[i];
1566  data[i] = NULL;
1567  }
1568  }
1569  return;
1570  } else if (static_cast<char>(i) == '\n' || static_cast<char>(i) == ';') {
1571  // End of matrix row.
1572  is.get();
1573  if (cur_row->size() != 0) {
1574  data.push_back(cur_row);
1575  cur_row = new std::vector<Real>;
1576  cur_row->reserve(data.back()->size());
1577  }
1578  } else if ( (i >= '0' && i <= '9') || i == '-' ) { // A number...
1579  Real r;
1580  is >> r;
1581  if (is.fail()) {
1582  specific_error << "Stream failure/EOF while reading matrix data.";
1583  goto cleanup;
1584  }
1585  cur_row->push_back(r);
1586  } else if (isspace(i)) {
1587  is.get(); // eat the space and do nothing.
1588  } else { // NaN or inf or error.
1589  std::string str;
1590  is >> str;
1591  if (!KALDI_STRCASECMP(str.c_str(), "inf") ||
1592  !KALDI_STRCASECMP(str.c_str(), "infinity")) {
1593  cur_row->push_back(std::numeric_limits<Real>::infinity());
1594  KALDI_WARN << "Reading infinite value into matrix.";
1595  } else if (!KALDI_STRCASECMP(str.c_str(), "nan")) {
1596  cur_row->push_back(std::numeric_limits<Real>::quiet_NaN());
1597  KALDI_WARN << "Reading NaN value into matrix.";
1598  } else {
1599  if (str.length() > 20) str = str.substr(0, 17) + "...";
1600  specific_error << "Expecting numeric matrix data, got " << str;
1601  goto cleanup;
1602  }
1603  }
1604  }
1605  // Note, we never leave the while () loop before this
1606  // line (we return from it.)
1607  cleanup: // We only reach here in case of error in the while loop above.
1608  if(cur_row != NULL)
1609  delete cur_row;
1610  for (size_t i = 0; i < data.size(); i++)
1611  if(data[i] != NULL)
1612  delete data[i];
1613  // and then go on to "bad" below, where we print error.
1614  }
1615 bad:
1616  KALDI_ERR << "Failed to read matrix from stream. " << specific_error.str()
1617  << " File position at start is "
1618  << pos_at_start << ", currently " << is.tellg();
1619 }
void ReadBasicType(std::istream &is, bool binary, T *t)
ReadBasicType is the name of the read function for bool, integer types, and floating-point types...
Definition: io-funcs-inl.h:55
Real * RowData(MatrixIndexT i)
Returns pointer to data for one row (non-const)
Definition: kaldi-matrix.h:84
void AddMat(const Real alpha, const MatrixBase< Real > &M, MatrixTransposeType transA=kNoTrans)
*this += alpha * M [or M^T]
void ReadToken(std::istream &is, bool binary, std::string *str)
ReadToken gets the next token and puts it in str (exception on failure).
Definition: io-funcs.cc:154
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
int Peek(std::istream &is, bool binary)
Peek consumes whitespace (if binary == false) and then returns the peek() value of the stream...
Definition: io-funcs.cc:145
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:767
MatrixIndexT Stride() const
Stride (distance in memory between each row). Will be >= NumCols.
Definition: kaldi-matrix.h:67
#define KALDI_ERR
Definition: kaldi-error.h:127
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:766
#define KALDI_WARN
Definition: kaldi-error.h:130
const Real * Data() const
Gives pointer to raw data (const).
Definition: kaldi-matrix.h:76
MatrixIndexT NumCols() const
Returns number of columns (or zero for emtpy matrix).
Definition: kaldi-matrix.h:64
friend class Matrix< Real >
Definition: kaldi-matrix.h:49
#define KALDI_STRCASECMP
Definition: kaldi-utils.h:147
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).
void RemoveRow ( MatrixIndexT  i)

Remove a specified row.

Definition at line 1117 of file kaldi-matrix.cc.

References rnnlm::j, and KALDI_ASSERT.

Referenced by FullGmm::Merge(), DiagGmm::Merge(), DiagGmm::RemoveComponent(), FullGmm::RemoveComponent(), and kaldi::UnitTestRemoveRow().

1117  {
1118  KALDI_ASSERT(static_cast<UnsignedMatrixIndexT>(i) <
1119  static_cast<UnsignedMatrixIndexT>(MatrixBase<Real>::num_rows_)
1120  && "Access out of matrix");
1121  for (MatrixIndexT j = i + 1; j < MatrixBase<Real>::num_rows_; j++)
1122  MatrixBase<Real>::Row(j-1).CopyFromVec( MatrixBase<Real>::Row(j));
1123  MatrixBase<Real>::num_rows_--;
1124 }
int32 MatrixIndexT
Definition: matrix-common.h:98
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:169
void Resize ( const MatrixIndexT  r,
const MatrixIndexT  c,
MatrixResizeType  resize_type = kSetZero,
MatrixStrideType  stride_type = kDefaultStride 
)

Sets matrix to a specified size (zero is OK as long as both r and c are zero).

The value of the new data depends on resize_type: -if kSetZero, the new data will be zero -if kUndefined, the new data will be undefined -if kCopyData, the new data will be the same as the old data in any shared positions, and zero elsewhere.

You can set stride_type to kStrideEqualNumCols to force the stride to equal the number of columns; by default it is set so that the stride in bytes is a multiple of 16.

This function takes time proportional to the number of data elements.

Definition at line 818 of file kaldi-matrix.cc.

References data_, kaldi::kCopyData, kaldi::kDefaultStride, kaldi::kSetZero, kaldi::kUndefined, MatrixBase< Real >::Range(), MatrixBase< Real >::SetZero(), and Matrix< Real >::Swap().

Referenced by DecodableMatrixMappedOffset::AcceptLoglikes(), OnlinePitchFeatureImpl::AcceptWaveform(), LdaEstimate::AddMeanOffset(), DecodableNnetLoopedOnlineBase::AdvanceChunk(), DecodableNnetSimpleLooped::AdvanceChunk(), kaldi::nnet2::AppendDiscriminativeExamples(), kaldi::AppendFeats(), kaldi::AppendPostToFeats(), kaldi::AppendVectorToFeats(), kaldi::ApplyPca(), Sgmm2Project::ApplyProjection(), Plda::ApplyTransform(), WaveData::Clear(), Sgmm2PerSpkDerivedVars::Clear(), GeneralMatrix::Clear(), SphinxMatrixHolder< kFeatDim >::Clear(), AmSgmm2::ComponentLogLikes(), kaldi::ComposeTransforms(), GeneralMatrix::Compress(), NnetComputerFromEg::Compute(), OfflineFeatureTpl< F >::Compute(), kaldi::ComputeAmGmmFeatureDeriv(), kaldi::ComputeAndProcessKaldiPitch(), kaldi::ComputeDeltas(), IvectorExtractor::ComputeDerivedVars(), kaldi::ComputeFeatureNormalizingTransform(), Fmpe::ComputeFeatures(), AmSgmm2::ComputeFmllrPreXform(), DecodableNnet2Online::ComputeForFrame(), kaldi::ComputeKaldiPitch(), kaldi::ComputeKaldiPitchFirstPass(), Sgmm2Project::ComputeLdaTransform(), kaldi::ComputePca(), AmSgmm2::ComputePerSpkDerivedVars(), Sgmm2Project::ComputeProjection(), kaldi::ComputeShiftedDeltas(), Fmpe::ComputeStddevs(), BasisFmllrEstimate::ComputeTransform(), kaldi::ConcatFeats(), FmllrRawAccs::ConvertToPerRowStats(), CompressedAffineXformStats::CopyFromAffineXformStats(), SvdApplier::DecomposeComponent(), DiscriminativeExampleSplitter::DoExcise(), DecodableNnetSimple::DoNnetComputation(), LdaEstimate::Estimate(), FeatureTransformEstimateMulti::Estimate(), FeatureTransformEstimate::EstimateInternal(), kaldi::EstimateIvectorsOnline(), FeatureTransformEstimateMulti::EstimateTransformPart(), kaldi::EstPca(), kaldi::ExtractObjectRange(), kaldi::FilterCompressedMatrixRows(), kaldi::FilterMatrixRows(), FmllrRawAccs::FmllrRawAccs(), Fmpe::Fmpe(), kaldi::nnet2::FormatNnetInput(), FullGmm::GetCovarsAndMeans(), kaldi::GetFeatDeriv(), LogisticRegression::GetLogPosteriors(), GeneralMatrix::GetMatrix(), FullGmm::GetMeans(), DiagGmm::GetMeans(), OnlineCmvn::GetMostRecentCachedFrame(), IvectorExtractorStats::GetOrthogonalIvectorTransform(), kaldi::GetOutput(), PldaEstimator::GetOutput(), OnlineCmvn::GetState(), DiagGmm::GetVars(), RegtreeFmllrDiagGmm::GetXformMatrix(), AmSgmm2::IncreasePhoneSpaceDim(), AmSgmm2::IncreaseSpkSpaceDim(), kaldi::IncreaseTransformDimension(), AffineXformStats::Init(), LdaEstimate::Init(), FmpeStats::Init(), kaldi::InitCmvnStats(), OnlinePreconditionerSimple::InitDefault(), OnlineNaturalGradientSimple::InitDefault(), kaldi::InitFmllr(), AmSgmm2::InitializeFromFullGmm(), AmSgmm2::InitializeMw(), AmSgmm2::InitializeNu(), kaldi::InitIdftBases(), IvectorExtractor::IvectorExtractor(), IvectorExtractorStats::IvectorExtractorStats(), MatrixBase< Real >::LapackGesvd(), kaldi::nnet2::LatticeToDiscriminativeExample(), AffineComponent::LimitRank(), DiagGmm::LogLikelihoods(), main(), Matrix< Real >::Matrix(), Matrix< BaseFloat >::Matrix(), FullGmm::Merge(), DiagGmm::Merge(), FullGmm::MergePreselect(), MfccComputer::MfccComputer(), LogisticRegression::MixUp(), kaldi::nnet2::NnetComputationChunked(), LimitRankClass::operator()(), Matrix< BaseFloat >::operator=(), kaldi::PosteriorToMatrix(), kaldi::PosteriorToPdfMatrix(), kaldi::ProcessPitch(), AffineXformStats::Read(), WaveData::Read(), AmSgmm2::Read(), SphinxMatrixHolder< kFeatDim >::Read(), kaldi::ReadData(), NnetExampleBackgroundReader::ReadExamples(), kaldi::nnet3::ReduceRankOfComponents(), AmSgmm2::RemoveSpeakerSpace(), DiagGmmNormal::Resize(), FullGmmNormal::Resize(), FullGmm::Resize(), DiagGmm::Resize(), AccumFullGmm::Resize(), AccumDiagGmm::Resize(), Sgmm2PerFrameDerivedVars::Resize(), MleAmSgmm2Accs::ResizeAccumulators(), kaldi::ReverseFrames(), KlHmm::SetStats(), LogisticRegression::SetWeights(), kaldi::SpliceFrames(), FullGmm::Split(), DiagGmm::Split(), CuMatrix< Real >::Swap(), TestSgmm2Fmllr(), LogisticRegression::Train(), kaldi::TransformIvectors(), kaldi::UnitTestAddMat2(), kaldi::UnitTestDelay(), UnitTestEstimateSgmm2(), kaldi::UnitTestIo(), UnitTestMleAmDiagGmm(), kaldi::UnitTestPieces(), kaldi::UnitTestResize(), kaldi::UnitTestResizeCopyDataDifferentStrideType(), kaldi::UnitTestTransposeScatter(), kaldi::nnet2::UpdateHash(), and UpdateWClass::UpdateWClass().

821  {
822  // the next block uses recursion to handle what we have to do if
823  // resize_type == kCopyData.
824  if (resize_type == kCopyData) {
825  if (this->data_ == NULL || rows == 0) resize_type = kSetZero; // nothing to copy.
826  else if (rows == this->num_rows_ && cols == this->num_cols_ &&
827  (stride_type == kDefaultStride || this->stride_ == this->num_cols_)) { return; } // nothing to do.
828  else {
829  // set tmp to a matrix of the desired size; if new matrix
830  // is bigger in some dimension, zero it.
831  MatrixResizeType new_resize_type =
832  (rows > this->num_rows_ || cols > this->num_cols_) ? kSetZero : kUndefined;
833  Matrix<Real> tmp(rows, cols, new_resize_type, stride_type);
834  MatrixIndexT rows_min = std::min(rows, this->num_rows_),
835  cols_min = std::min(cols, this->num_cols_);
836  tmp.Range(0, rows_min, 0, cols_min).
837  CopyFromMat(this->Range(0, rows_min, 0, cols_min));
838  tmp.Swap(this);
839  // and now let tmp go out of scope, deleting what was in *this.
840  return;
841  }
842  }
843  // At this point, resize_type == kSetZero or kUndefined.
844 
845  if (MatrixBase<Real>::data_ != NULL) {
846  if (rows == MatrixBase<Real>::num_rows_
847  && cols == MatrixBase<Real>::num_cols_) {
848  if (resize_type == kSetZero)
849  this->SetZero();
850  return;
851  }
852  else
853  Destroy();
854  }
855  Init(rows, cols, stride_type);
856  if (resize_type == kSetZero) MatrixBase<Real>::SetZero();
857 }
MatrixResizeType
Definition: matrix-common.h:37
MatrixIndexT stride_
< Number of rows
Definition: kaldi-matrix.h:770
Real * data_
data memory area
Definition: kaldi-matrix.h:762
void Init(const MatrixIndexT r, const MatrixIndexT c, const MatrixStrideType stride_type)
Init assumes the current class contents are invalid (i.e.
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
uint64 data_
int32 MatrixIndexT
Definition: matrix-common.h:98
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:767
SubMatrix< Real > Range(const MatrixIndexT row_offset, const MatrixIndexT num_rows, const MatrixIndexT col_offset, const MatrixIndexT num_cols) const
Return a sub-part of matrix.
Definition: kaldi-matrix.h:199
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:766
void SetZero()
Sets matrix to zero.
void Destroy()
Deallocates memory and sets to empty matrix (dimension 0, 0).
friend class Matrix< Real >
Definition: kaldi-matrix.h:49
void Swap ( Matrix< Real > *  other)

Swaps the contents of *this and *other. Shallow swap.

Definition at line 2209 of file kaldi-matrix.cc.

References data_, MatrixBase< Real >::data_, MatrixBase< Real >::num_cols_, MatrixBase< Real >::num_rows_, MatrixBase< Real >::stride_, and kaldi::swap().

Referenced by DecodableMatrixMappedOffset::AcceptLoglikes(), DecodableNnetLoopedOnlineBase::AdvanceChunk(), DecodableNnetSimpleLooped::AdvanceChunk(), DecodableAmNnet::DecodableAmNnet(), NnetExampleBackgroundReader::GetNextMinibatch(), Matrix< Real >::Resize(), WaveData::Swap(), GeneralMatrix::Swap(), CuMatrix< Real >::Swap(), SphinxMatrixHolder< kFeatDim >::Swap(), GeneralMatrix::SwapFullMatrix(), and kaldi::UnitTestIvectorExtractor().

2209  {
2210  std::swap(this->data_, other->data_);
2211  std::swap(this->num_cols_, other->num_cols_);
2212  std::swap(this->num_rows_, other->num_rows_);
2213  std::swap(this->stride_, other->stride_);
2214 }
MatrixIndexT stride_
< Number of rows
Definition: kaldi-matrix.h:770
Real * data_
data memory area
Definition: kaldi-matrix.h:762
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:767
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:766
void Swap ( CuMatrix< Real > *  mat)

Defined in ../cudamatrix/cu-matrix.cc.

Definition at line 3127 of file cu-matrix.cc.

References CuMatrix< Real >::Swap().

3127 { mat->Swap(this); }
void Transpose ( )

Transpose the matrix.

Works for non-square matrices as well as square ones.

Definition at line 2090 of file kaldi-matrix.cc.

References kaldi::kTrans.

Referenced by kaldi::ComputePca(), BasisFmllrEstimate::ComputeTransform(), kaldi::CuVectorUnitTestCopyDiagFromMat(), BasisFmllrEstimate::EstimateFmllrBasis(), kaldi::UnitTestAddDiagVecMat(), kaldi::UnitTestAddMat2Sp(), kaldi::UnitTestAddMatSmat(), kaldi::UnitTestCuMatrixTranspose(), kaldi::UnitTestSymAddMat2(), kaldi::UnitTestTranspose(), kaldi::UnitTestVecmul(), and MlltAccs::Update().

2090  {
2091  if (this->num_rows_ != this->num_cols_) {
2092  Matrix<Real> tmp(*this, kTrans);
2093  Resize(this->num_cols_, this->num_rows_);
2094  this->CopyFromMat(tmp);
2095  } else {
2096  (static_cast<MatrixBase<Real>&>(*this)).Transpose();
2097  }
2098 }
void Transpose()
Transpose the matrix.
void CopyFromMat(const MatrixBase< OtherReal > &M, MatrixTransposeType trans=kNoTrans)
Copy given matrix. (no resize is done).
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:767
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:766
friend class Matrix< Real >
Definition: kaldi-matrix.h:49
void Resize(const MatrixIndexT r, const MatrixIndexT c, MatrixResizeType resize_type=kSetZero, MatrixStrideType stride_type=kDefaultStride)
Sets matrix to a specified size (zero is OK as long as both r and c are zero).

The documentation for this singleton was generated from the following files: