Published
Edited
Apr 25, 2018
1 fork
Importers
7 stars
Insert cell
Insert cell
latex_matrix([[1,0],[0,1]])
Insert cell
tex`${latex_matrix([[1,0],[0,1]])}`
Insert cell
tex`${
latex_matrix(
[...Array(20).keys()]
.map(row => [...Array(20).keys()]
.map(col => col+row))
)
}`
Insert cell
tex`${
latex_matrix(
[...Array(20).keys()]
.map(row => [...Array(20).keys()]),
{'max_cols':20}
)
}`
Insert cell
latex_matrix = function(matrix, options={})
{
/** Returns the latex representation of a matrix given by a 2-dimensional array
Arguments:
matrix: Row-first layout 2-dimensional array representing a matrix.
matrix.length is the number of rows and
matrix[c].length ∀c is the number of columns.
options: Object like {
max_rows: Maximum number of rows to display. max_rows ≥ 4.
max_cols: Maximum number of columns to display. max_cols ≥ 4.
formatter: Function mapping a matrix element to a string.
}
*/
// Default 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;
}
// Assert that all rows have the same length
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}";
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more