@@ -609,18 +609,41 @@ export class Mat {
609609 return ret ;
610610 }
611611
612- //
612+ //set how many digits kept while display the matirx
613613 setDigits ( x : number ) {
614614 this . digits = x ;
615615 return this ;
616616 }
617- //return the format of matrix as a CSV string
617+
618+ /*serialize matrix to JavaScript 2D Array string, for example:
619+ [[1,2],
620+ [3,4]]
621+ (Users should directly copy the string as a JS 2D Array into their code)
622+ */
623+
618624 toString ( ) : string {
625+ let rowStringList = this . val . map ( eachRow => { return eachRow . map ( eachValue => {
626+ if ( this . digits <= 0 ) return String ( eachValue ) ;
627+ else return String ( eachValue . toFixed ( this . digits ) )
628+ } ) . reduce ( ( rowAccumulator , currentElementString ) => rowAccumulator + "," + currentElementString ) } )
629+
630+ let returnString = "" ;
631+ for ( let rowIndex = 0 ; rowIndex < rowStringList . length ; rowIndex += 1 ) {
632+ returnString += "[" + rowStringList [ rowIndex ] + "]" + ( ( rowIndex === rowStringList . length - 1 ) ?"" :",\n" )
633+ }
634+ return "\n[" + returnString + "]\n"
635+ }
636+
637+ /*serialize matrix to 2D Array with Tab, for example:
638+ 1 2
639+ 3 4
640+ */
641+ toStringWithTab ( ) :string {
619642 let returnString = '' ;
620643 for ( let i = 0 ; i < this . rows ; i ++ ) {
621644 for ( let j = 0 ; j < this . cols ; j ++ ) {
622645 // if keeps all digits
623- if ( this . digits === - 1 ) {
646+ if ( this . digits <= 0 ) {
624647 if ( j === 0 ) {
625648 returnString += String ( this . val [ i ] [ j ] ) ;
626649 } else {
@@ -636,16 +659,20 @@ export class Mat {
636659 }
637660 if ( i !== this . rows - 1 ) returnString += '\n' ;
638661 }
639-
640662 return returnString + '\n' ;
641663 }
664+
665+ //return the format of matrix as a CSV string
642666 toCsv ( ) : string {
643667 return mat2csv ( this ) ;
644668 }
669+
670+ //return the string of current object in JSON format
645671 toJson ( ) : string {
646672 return JSON . stringify ( this ) ;
647673 }
648674
675+ //return the matrix in TeX format
649676 toTex ( ) : string {
650677 let returnString = '\\begin{bmatrix} ' ;
651678 for ( let i = 0 ; i < this . rows ; i ++ ) {
0 commit comments