Showing results for 
Show  only  | Search instead for 
Did you mean: 
Choose Language Hide Translation Bar
Convert Matrix to Data Table and Back


You have data in a Matrix and need a Data Table, or the other way 'round

Data table or matrix?Data table or matrix?


There is a function, AsTable(), that makes a new data table from a matrix, and a data table method, GetAsMatrix(), that makes a matrix from the numeric columns in a table.

There is also a way to index data tables directly with data table subscripting.

// make a matrix of 5 rows, 3 cols, random values
mat = J( 5, 3, Random Normal() );
// make a data table from a matrix
dt = As Table( mat );
// make a matrix from a data table
mat2 = dt << GetAsMatrix;
// comparing two matrices returns a matrix of answers
// and the All function returns true if all of the
// matrix values are true
Show( All( mat == mat2 ) );
// use data table subscripting to get a matrix of all
// rows and all columns from the table; the zero subscript
// is used with matrix and data table to mean "all
// rows or all columns"
mat3 = dt[0, 0];
Show( All( mat == mat3 ) );


<<GetAsMatrix can also specify the columns several ways, see the scripting index. AsTable can also name the columns, see the scripting index. The data table subscripting method has many more possibilities than this example suggests.

See Also


Thanks, very useful , and any convient way to get a row vector from a data table?



 Data table subscripting describes indexing a data table as a matrix, and What is the JSL Matrix? shows how to use matrix subscripting. So, with a data table (or a matrix), rather than copying the data out of the table to make a matrix, you can get a row from either one like this:

// if dt is a table...
rowVector = dt[ rowNumber, 0 ]; // all columns
rowVector = dt[ rowNumber, { age, height, weight } ]; // selected columns
// if m is a matrix
rowVector = m[ row, 0 ];
rowVector = m[ row, 5::9 ]; // selected items from row
// and both dimensions at once
patch = m[ 3::5, 7::11 ];

The zero subscript means "all of this dimension". The matrix indexing starts at one.

JSL Cookbook

If you’re looking for a code snippet or design pattern that performs a common task for your JSL project, the JSL Cookbook is for you.

This knowledge base contains building blocks of JSL code that you can use to reduce the amount of coding you have to do yourself.

It's also a great place to learn from the experts how to use JSL in new ways, with best practices.