latex_matrix = function(matrix, options={})
{
if (!('max_rows' in options)) options.max_rows = 10;
if (!('max_cols' in options)) options.max_cols = 10;
if (!('formatter' in options)) options.formatter = function(element) {
if ((Number(element) === element) && (element%1 !== 0))
return element.toFixed(2);
return element;
}
if (!matrix.map(row => row.length).reduce((a,b) => (a===b) ? a : NaN))
throw Error('latex_matrix expects all rows to have the same length.');
const rows = matrix.length;
const cols = matrix[0].length;
options.max_rows = Math.max(4, options.max_rows);
options.max_cols = Math.max(4, options.max_cols);
const rows_range = (rows <= options.max_rows) ?
[...Array(rows).keys()] :
[0, 1, 'dots', rows-2, rows-1];
const cols_range = (cols <= options.max_cols)?
[...Array(cols).keys()] :
[0, 1, 'dots', cols-2, cols-1];
function element_map(row, col) {
if ((row == 'dots') && (col == 'dots')) return '\\ddots';
if (row == 'dots') return '\\vdots';
if (col == 'dots') return '\\cdots';
return options.formatter(matrix[row][col]);
}
const latex_entries = rows_range
.map(row => cols_range
.map(col => element_map(row,col))
.join(' & '))
.join(' \\\\\n');
return "\\begin{bmatrix}\n"+latex_entries+"\n\\end{bmatrix}";
}