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...
 
- 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 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 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 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<>
void AddVecVec (const float alpha, const VectorBase< float > &a, const VectorBase< float > &rb)
 
template<>
void AddVecVec (const double alpha, const VectorBase< double > &a, const VectorBase< double > &rb)
 
template<>
void CopyFromSp (const SpMatrix< float > &M)
 
template<>
void CopyFromSp (const SpMatrix< double > &M)
 

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 743 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 750 of file kaldi-matrix.h.

752  :
753  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 841 of file cu-matrix.h.

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

842  {
843  if (trans == kNoTrans) Init(M.NumRows(), M.NumCols(), kDefaultStride);
844  else Init(M.NumCols(), M.NumRows(), kDefaultStride);
845  M.CopyToMat(this, trans);
846 }
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.

Definition at line 590 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().

592  : MatrixBase<Real>() {
593  if (trans == kNoTrans) {
594  Resize(M.num_rows_, M.num_cols_);
595  this->CopyFromMat(M);
596  } else {
597  Resize(M.num_cols_, M.num_rows_);
598  this->CopyFromMat(M, kTrans);
599  }
600 }
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)

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

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

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

604  :
605  MatrixBase<Real>() {
606  Resize(M.num_rows_, M.num_cols_);
607  this->CopyFromMat(M);
608 }
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 = kNoTrans 
)
explicit

Copy constructor: as above, but from another type.

Copy constructor from another type.

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

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

614  : MatrixBase<Real>() {
615  if (trans == kNoTrans) {
616  Resize(M.NumRows(), M.NumCols());
617  this->CopyFromMat(M);
618  } else {
619  Resize(M.NumCols(), M.NumRows());
620  this->CopyFromMat(M, kTrans);
621  }
622 }
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 SpMatrix< OtherReal > &  M)
inlineexplicit

Copy constructor taking SpMatrix...

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

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

784  : MatrixBase<Real>() {
785  Resize(M.NumRows(), M.NumRows(), kUndefined);
786  this->CopyFromSp(M);
787  }
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.

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

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

1908  : MatrixBase<Real>() {
1909  Resize(M.NumRows(), M.NumCols(), kUndefined);
1910  M.CopyToMat(this);
1911 }
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 TpMatrix< OtherReal > &  M,
MatrixTransposeType  trans = kNoTrans 
)
inlineexplicit

Copy constructor taking TpMatrix...

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

795  : MatrixBase<Real>() {
796  if (trans == kNoTrans) {
797  Resize(M.NumRows(), M.NumCols(), kUndefined);
798  this->CopyFromTp(M);
799  } else {
800  Resize(M.NumCols(), M.NumRows(), kUndefined);
801  this->CopyFromTp(M, kTrans);
802  }
803  }
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 817 of file kaldi-matrix.h.

817 { Destroy(); }
void Destroy()
Deallocates memory and sets to empty matrix (dimension 0, 0).

Member Function Documentation

void Destroy ( )
private

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

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

References KALDI_MEMALIGN_FREE.

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

977  {
978  // we need to free the data block if it was defined
979  if (NULL != MatrixBase<Real>::data_)
982  MatrixBase<Real>::num_rows_ = MatrixBase<Real>::num_cols_
983  = MatrixBase<Real>::stride_ = 0;
984 }
uint64 data_
#define KALDI_MEMALIGN_FREE(x)
Definition: kaldi-utils.h:56
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 633 of file kaldi-matrix.cc.

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

635  {
636  if (rows * cols == 0) {
637  KALDI_ASSERT(rows == 0 && cols == 0);
638  this->num_rows_ = 0;
639  this->num_cols_ = 0;
640  this->stride_ = 0;
641  this->data_ = NULL;
642  return;
643  }
644  KALDI_ASSERT(rows > 0 && cols > 0);
645  MatrixIndexT skip, stride;
646  size_t size;
647  void *data; // aligned memory block
648  void *temp; // memory block to be really freed
649 
650  // compute the size of skip and real cols
651  skip = ((16 / sizeof(Real)) - cols % (16 / sizeof(Real)))
652  % (16 / sizeof(Real));
653  stride = cols + skip;
654  size = static_cast<size_t>(rows) * static_cast<size_t>(stride)
655  * sizeof(Real);
656 
657  // allocate the memory and set the right dimensions and parameters
658  if (NULL != (data = KALDI_MEMALIGN(16, size, &temp))) {
659  MatrixBase<Real>::data_ = static_cast<Real *> (data);
660  MatrixBase<Real>::num_rows_ = rows;
661  MatrixBase<Real>::num_cols_ = cols;
662  MatrixBase<Real>::stride_ = (stride_type == kDefaultStride ? stride : cols);
663  } else {
664  throw std::bad_alloc();
665  }
666 }
MatrixIndexT stride_
< Number of rows
Definition: kaldi-matrix.h:736
Real * data_
data memory area
Definition: kaldi-matrix.h:728
uint64 data_
int32 MatrixIndexT
Definition: matrix-common.h:96
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:733
#define KALDI_MEMALIGN(align, size, pp_orig)
Definition: kaldi-utils.h:54
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:732
#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 837 of file kaldi-matrix.h.

837  {
838  if (MatrixBase<Real>::NumRows() != other.NumRows() ||
839  MatrixBase<Real>::NumCols() != other.NumCols())
840  Resize(other.NumRows(), other.NumCols(), kUndefined);
842  return *this;
843  }
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:61
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 846 of file kaldi-matrix.h.

846  {
847  if (MatrixBase<Real>::NumRows() != other.NumRows() ||
848  MatrixBase<Real>::NumCols() != other.NumCols())
849  Resize(other.NumRows(), other.NumCols(), kUndefined);
851  return *this;
852  }
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:61
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 1299 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(), Plda::Read(), MleAmSgmm2Accs::Read(), FullGmm::Read(), CompressedMatrix::Read(), DiagGmm::Read(), DiscriminativeNnetExample::Read(), Fmpe::Read(), AmSgmm2::Read(), IvectorExtractor::Read(), GeneralMatrix::Read(), OnlineCmvnState::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().

1299  {
1300  if (add) {
1301  Matrix<Real> tmp;
1302  tmp.Read(is, binary, false); // read without adding.
1303  if (this->num_rows_ == 0) this->Resize(tmp.num_rows_, tmp.num_cols_);
1304  else {
1305  if (this->num_rows_ != tmp.num_rows_ || this->num_cols_ != tmp.num_cols_) {
1306  if (tmp.num_rows_ == 0) return; // do nothing in this case.
1307  else KALDI_ERR << "Matrix::Read, size mismatch "
1308  << this->num_rows_ << ", " << this->num_cols_
1309  << " vs. " << tmp.num_rows_ << ", " << tmp.num_cols_;
1310  }
1311  }
1312  this->AddMat(1.0, tmp);
1313  return;
1314  }
1315 
1316  // now assume add == false.
1317  MatrixIndexT pos_at_start = is.tellg();
1318  std::ostringstream specific_error;
1319 
1320  if (binary) { // Read in binary mode.
1321  int peekval = Peek(is, binary);
1322  if (peekval == 'C') {
1323  // This code enable us to read CompressedMatrix as a regular matrix.
1324  CompressedMatrix compressed_mat;
1325  compressed_mat.Read(is, binary); // at this point, add == false.
1326  this->Resize(compressed_mat.NumRows(), compressed_mat.NumCols());
1327  compressed_mat.CopyToMat(this);
1328  return;
1329  }
1330  const char *my_token = (sizeof(Real) == 4 ? "FM" : "DM");
1331  char other_token_start = (sizeof(Real) == 4 ? 'D' : 'F');
1332  if (peekval == other_token_start) { // need to instantiate the other type to read it.
1333  typedef typename OtherReal<Real>::Real OtherType; // if Real == float, OtherType == double, and vice versa.
1334  Matrix<OtherType> other(this->num_rows_, this->num_cols_);
1335  other.Read(is, binary, false); // add is false at this point anyway.
1336  this->Resize(other.NumRows(), other.NumCols());
1337  this->CopyFromMat(other);
1338  return;
1339  }
1340  std::string token;
1341  ReadToken(is, binary, &token);
1342  if (token != my_token) {
1343  specific_error << ": Expected token " << my_token << ", got " << token;
1344  goto bad;
1345  }
1346  int32 rows, cols;
1347  ReadBasicType(is, binary, &rows); // throws on error.
1348  ReadBasicType(is, binary, &cols); // throws on error.
1349  if ((MatrixIndexT)rows != this->num_rows_ || (MatrixIndexT)cols != this->num_cols_) {
1350  this->Resize(rows, cols);
1351  }
1352  if (this->Stride() == this->NumCols() && rows*cols!=0) {
1353  is.read(reinterpret_cast<char*>(this->Data()),
1354  sizeof(Real)*rows*cols);
1355  if (is.fail()) goto bad;
1356  } else {
1357  for (MatrixIndexT i = 0; i < (MatrixIndexT)rows; i++) {
1358  is.read(reinterpret_cast<char*>(this->RowData(i)), sizeof(Real)*cols);
1359  if (is.fail()) goto bad;
1360  }
1361  }
1362  if (is.eof()) return;
1363  if (is.fail()) goto bad;
1364  return;
1365  } else { // Text mode.
1366  std::string str;
1367  is >> str; // get a token
1368  if (is.fail()) { specific_error << ": Expected \"[\", got EOF"; goto bad; }
1369  // if ((str.compare("DM") == 0) || (str.compare("FM") == 0)) { // Back compatibility.
1370  // is >> str; // get #rows
1371  // is >> str; // get #cols
1372  // is >> str; // get "["
1373  // }
1374  if (str == "[]") { Resize(0, 0); return; } // Be tolerant of variants.
1375  else if (str != "[") {
1376  specific_error << ": Expected \"[\", got \"" << str << '"';
1377  goto bad;
1378  }
1379  // At this point, we have read "[".
1380  std::vector<std::vector<Real>* > data;
1381  std::vector<Real> *cur_row = new std::vector<Real>;
1382  while (1) {
1383  int i = is.peek();
1384  if (i == -1) { specific_error << "Got EOF while reading matrix data"; goto cleanup; }
1385  else if (static_cast<char>(i) == ']') { // Finished reading matrix.
1386  is.get(); // eat the "]".
1387  i = is.peek();
1388  if (static_cast<char>(i) == '\r') {
1389  is.get();
1390  is.get(); // get \r\n (must eat what we wrote)
1391  } else if (static_cast<char>(i) == '\n') { is.get(); } // get \n (must eat what we wrote)
1392  if (is.fail()) {
1393  KALDI_WARN << "After end of matrix data, read error.";
1394  // we got the data we needed, so just warn for this error.
1395  }
1396  // Now process the data.
1397  if (!cur_row->empty()) data.push_back(cur_row);
1398  else delete(cur_row);
1399  cur_row = NULL;
1400  if (data.empty()) { this->Resize(0, 0); return; }
1401  else {
1402  int32 num_rows = data.size(), num_cols = data[0]->size();
1403  this->Resize(num_rows, num_cols);
1404  for (int32 i = 0; i < num_rows; i++) {
1405  if (static_cast<int32>(data[i]->size()) != num_cols) {
1406  specific_error << "Matrix has inconsistent #cols: " << num_cols
1407  << " vs." << data[i]->size() << " (processing row"
1408  << i << ")";
1409  goto cleanup;
1410  }
1411  for (int32 j = 0; j < num_cols; j++)
1412  (*this)(i, j) = (*(data[i]))[j];
1413  delete data[i];
1414  data[i] = NULL;
1415  }
1416  }
1417  return;
1418  } else if (static_cast<char>(i) == '\n' || static_cast<char>(i) == ';') {
1419  // End of matrix row.
1420  is.get();
1421  if (cur_row->size() != 0) {
1422  data.push_back(cur_row);
1423  cur_row = new std::vector<Real>;
1424  cur_row->reserve(data.back()->size());
1425  }
1426  } else if ( (i >= '0' && i <= '9') || i == '-' ) { // A number...
1427  Real r;
1428  is >> r;
1429  if (is.fail()) {
1430  specific_error << "Stream failure/EOF while reading matrix data.";
1431  goto cleanup;
1432  }
1433  cur_row->push_back(r);
1434  } else if (isspace(i)) {
1435  is.get(); // eat the space and do nothing.
1436  } else { // NaN or inf or error.
1437  std::string str;
1438  is >> str;
1439  if (!KALDI_STRCASECMP(str.c_str(), "inf") ||
1440  !KALDI_STRCASECMP(str.c_str(), "infinity")) {
1441  cur_row->push_back(std::numeric_limits<Real>::infinity());
1442  KALDI_WARN << "Reading infinite value into matrix.";
1443  } else if (!KALDI_STRCASECMP(str.c_str(), "nan")) {
1444  cur_row->push_back(std::numeric_limits<Real>::quiet_NaN());
1445  KALDI_WARN << "Reading NaN value into matrix.";
1446  } else {
1447  specific_error << "Expecting numeric matrix data, got " << str;
1448  goto cleanup;
1449  }
1450  }
1451  }
1452  // Note, we never leave the while () loop before this
1453  // line (we return from it.)
1454  cleanup: // We only reach here in case of error in the while loop above.
1455  if(cur_row != NULL)
1456  delete cur_row;
1457  for (size_t i = 0; i < data.size(); i++)
1458  if(data[i] != NULL)
1459  delete data[i];
1460  // and then go on to "bad" below, where we print error.
1461  }
1462 bad:
1463  KALDI_ERR << "Failed to read matrix from stream. " << specific_error.str()
1464  << " File position at start is "
1465  << pos_at_start << ", currently " << is.tellg();
1466 }
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:81
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:96
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:733
MatrixIndexT Stride() const
Stride (distance in memory between each row). Will be >= NumCols.
Definition: kaldi-matrix.h:64
#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:732
#define KALDI_WARN
Definition: kaldi-error.h:130
const Real * Data() const
Gives pointer to raw data (const).
Definition: kaldi-matrix.h:73
MatrixIndexT NumCols() const
Returns number of columns (or zero for emtpy matrix).
Definition: kaldi-matrix.h:61
friend class Matrix< Real >
Definition: kaldi-matrix.h:48
#define KALDI_STRCASECMP
Definition: kaldi-utils.h:140
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 967 of file kaldi-matrix.cc.

References rnnlm::j, and KALDI_ASSERT.

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

967  {
968  KALDI_ASSERT(static_cast<UnsignedMatrixIndexT>(i) <
969  static_cast<UnsignedMatrixIndexT>(MatrixBase<Real>::num_rows_)
970  && "Access out of matrix");
971  for (MatrixIndexT j = i + 1; j < MatrixBase<Real>::num_rows_; j++)
972  MatrixBase<Real>::Row(j-1).CopyFromVec( MatrixBase<Real>::Row(j));
973  MatrixBase<Real>::num_rows_--;
974 }
int32 MatrixIndexT
Definition: matrix-common.h:96
#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 669 of file kaldi-matrix.cc.

References data_, kaldi::kCopyData, 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(), Sgmm2Project::ApplyProjection(), 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(), DiscriminativeExampleSplitter::DoExcise(), DecodableNnetSimple::DoNnetComputation(), LdaEstimate::Estimate(), FeatureTransformEstimateMulti::Estimate(), FeatureTransformEstimate::EstimateInternal(), kaldi::EstimateIvectorsOnline(), FeatureTransformEstimateMulti::EstimateTransformPart(), 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< BaseFloat >::Matrix(), Matrix< Real >::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::ReadHtk(), AmSgmm2::RemoveSpeakerSpace(), DiagGmmNormal::Resize(), FullGmm::Resize(), FullGmmNormal::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::UnitTestAddMat2(), kaldi::UnitTestDelay(), UnitTestEstimateSgmm2(), kaldi::UnitTestIo(), UnitTestMleAmDiagGmm(), kaldi::UnitTestPieces(), kaldi::UnitTestResize(), kaldi::UnitTestTransposeScatter(), kaldi::nnet2::UpdateHash(), and UpdateWClass::UpdateWClass().

672  {
673  // the next block uses recursion to handle what we have to do if
674  // resize_type == kCopyData.
675  if (resize_type == kCopyData) {
676  if (this->data_ == NULL || rows == 0) resize_type = kSetZero; // nothing to copy.
677  else if (rows == this->num_rows_ && cols == this->num_cols_) { return; } // nothing to do.
678  else {
679  // set tmp to a matrix of the desired size; if new matrix
680  // is bigger in some dimension, zero it.
681  MatrixResizeType new_resize_type =
682  (rows > this->num_rows_ || cols > this->num_cols_) ? kSetZero : kUndefined;
683  Matrix<Real> tmp(rows, cols, new_resize_type);
684  MatrixIndexT rows_min = std::min(rows, this->num_rows_),
685  cols_min = std::min(cols, this->num_cols_);
686  tmp.Range(0, rows_min, 0, cols_min).
687  CopyFromMat(this->Range(0, rows_min, 0, cols_min));
688  tmp.Swap(this);
689  // and now let tmp go out of scope, deleting what was in *this.
690  return;
691  }
692  }
693  // At this point, resize_type == kSetZero or kUndefined.
694 
695  if (MatrixBase<Real>::data_ != NULL) {
696  if (rows == MatrixBase<Real>::num_rows_
697  && cols == MatrixBase<Real>::num_cols_) {
698  if (resize_type == kSetZero)
699  this->SetZero();
700  return;
701  }
702  else
703  Destroy();
704  }
705  Init(rows, cols, stride_type);
706  if (resize_type == kSetZero) MatrixBase<Real>::SetZero();
707 }
MatrixResizeType
Definition: matrix-common.h:35
Real * data_
data memory area
Definition: kaldi-matrix.h:728
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:96
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:733
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:196
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:732
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:48
void Swap ( Matrix< Real > *  other)

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

Definition at line 2043 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(), MatrixExponential< Real >::BackpropTaylor(), DecodableAmNnet::DecodableAmNnet(), NnetExampleBackgroundReader::GetNextMinibatch(), Matrix< Real >::Resize(), WaveData::Swap(), GeneralMatrix::Swap(), CuMatrix< Real >::Swap(), SphinxMatrixHolder< kFeatDim >::Swap(), GeneralMatrix::SwapFullMatrix(), and kaldi::UnitTestIvectorExtractor().

2043  {
2044  std::swap(this->data_, other->data_);
2045  std::swap(this->num_cols_, other->num_cols_);
2046  std::swap(this->num_rows_, other->num_rows_);
2047  std::swap(this->stride_, other->stride_);
2048 }
MatrixIndexT stride_
< Number of rows
Definition: kaldi-matrix.h:736
Real * data_
data memory area
Definition: kaldi-matrix.h:728
void swap(basic_filebuf< CharT, Traits > &x, basic_filebuf< CharT, Traits > &y)
MatrixIndexT num_rows_
< Number of columns
Definition: kaldi-matrix.h:733
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:732
void Swap ( CuMatrix< Real > *  mat)

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

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

References CuMatrix< Real >::Swap().

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

Transpose the matrix.

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

Definition at line 1937 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().

1937  {
1938  if (this->num_rows_ != this->num_cols_) {
1939  Matrix<Real> tmp(*this, kTrans);
1940  Resize(this->num_cols_, this->num_rows_);
1941  this->CopyFromMat(tmp);
1942  } else {
1943  (static_cast<MatrixBase<Real>&>(*this)).Transpose();
1944  }
1945 }
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:733
MatrixIndexT num_cols_
these atributes store the real matrix size as it is stored in memory including memalignment ...
Definition: kaldi-matrix.h:732
friend class Matrix< Real >
Definition: kaldi-matrix.h:48
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: