matrix namespace
matrix
Section titled “matrix”Overview
Section titled “Overview”The matrix namespace stores tabular data in a fixed number of rows and columns. Matrices are typed (matrix.new<float>, matrix.new<int>, etc.), so every cell obeys the same primitive type. After creating a matrix you can query its shape, update individual cells, add rows or columns, transpose it, or multiply it by other matrices, scalars, or vectors.
Each script can allocate only so many matrices. Increase max_matrix_count in the indicator() or strategy() call when you need to persist several objects at once.
Common helpers
Section titled “Common helpers”| Function | Purpose |
|---|---|
matrix.new<type>(rows, columns, value) | Allocate a typed matrix and prefill it with value (default na). |
matrix.rows(id) / matrix.columns(id) | Return the number of rows or columns. |
matrix.get(id, row, column) / matrix.set(id, row, column, value) | Read or write a cell (0-indexed). |
matrix.fill(id, value, from_row, to_row, from_column, to_column) | Bulk update a rectangular region. |
matrix.add_row(id, row, array_id) / matrix.add_col(id, column, array_id) | Insert new rows or columns. |
matrix.transpose(id) | Swap rows and columns, returning a new matrix. |
matrix.mult(id1, id2) | Multiply matrices, a matrix and scalar, or a matrix and array vector. |
Example
Section titled “Example”//@version=5indicator("Matrix-weighted blend", overlay=false, max_matrix_count=2, max_labels_count=1)
length = input.int(34, "Smoothing length", minval=2)
// Create a 1x2 matrix that stores the weights for two features.var weights = matrix.new<float>(1, 2, na)if barstate.isfirst matrix.set(weights, 0, 0, 0.6) matrix.set(weights, 0, 1, 0.4)
emaVal = ta.ema(close, length)
// Build a feature vector and project it with the weights matrix.featureVector = array.from(close, emaVal)projection = matrix.mult(weights, featureVector)blended = matrix.get(projection, 0, 0)
plot(close, "Close", color=color.gray)plot(blended, "Weighted close", color=color.teal, linewidth=2)
// Display the matrix shape on the last bar.if barstate.islastconfirmedhistory shape = str.tostring(matrix.rows(weights)) + "x" + str.tostring(matrix.columns(weights)) label.new(bar_index, blended, "matrix shape: " + shape, style=label.style_label_left, textcolor=color.white, bgcolor=color.new(color.blue, 65))