Problem
You have data in a Matrix and need a Data Table, or the other way 'round
Data table or matrix?Data table or matrix?Data table or matrix?
Solution
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 ) );
Thanks!
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.
Thanks, very useful , and any convient way to get a row vector from a data table?
Thanks!