Home » Mathemtical Functions » Understanding the matrix.diff() Function in Pine Script

Understanding the matrix.diff() Function in Pine Script

Photo of author
Published on

In this article, we delve into the functionality and application of the matrix.diff() function in Pine Script, focusing on its two primary overloads. This function is instrumental in performing subtraction operations between matrices or between a matrix and a scalar value. Through detailed examples, we’ll explore how to utilize this function to manipulate matrices effectively in Pine Script programming.

Syntax

The matrix.diff() function comes in two overloads, allowing for flexible operations on matrices:

  • matrix.diff(id1, id2) → matrix<int>
  • matrix.diff(id1, id2) → matrix<float>

Arguments

  • id1 (matrix<int>): The matrix from which subtraction will occur.
  • id2 (series int/float/matrix<int>): Can be a matrix object or a scalar value that will be subtracted from id1.

Examples

Difference Between Two Matrices

Let’s start with an example illustrating the subtraction between two matrices.

//@version=5
indicator("`matrix.diff()` Example 1")

if barstate.islastconfirmedhistory
    var matrixA = matrix.new<float>(2, 3, 5) // Matrix A with 2x3 dimensions, filled with `5`.
    var matrixB = matrix.new<float>(2, 3, 4) // Matrix B with 2x3 dimensions, filled with `4`.
    var resultMatrix = matrix.diff(matrixA, matrixB) // Resulting matrix from subtracting B from A.
    
    var displayTable = table.new(position.top_right, 1, 2, color.green)
    table.cell(displayTable, 0, 0, "Matrix A - Matrix B:")
    table.cell(displayTable, 0, 1, str.tostring(resultMatrix))
Examples

Detailed Walkthrough

  1. Indicator Declaration: The script starts with the //@version=5 directive, specifying that the script uses version 5 of Pine Script. It then declares an indicator with a title using indicator("title"), which will be shown in the TradingView indicator library and on the chart.
  2. Conditional Execution: The code checks if the current bar is the last confirmed historical bar using if barstate.islastconfirmedhistory. This condition ensures that the matrix operations and table display logic run only once, reducing the script’s computational load.
  3. Matrix Creation:
    • var matrixA = matrix.new<float>(2, 3, 5): Initializes a new matrix named matrixA with dimensions 2×3 (2 rows and 3 columns), filling all elements with the float value 5. This matrix serves as the minuend in the subtraction operation.
    • var matrixB = matrix.new<float>(2, 3, 4): Initializes another matrix named matrixB with the same dimensions, filled with the float value 4. This matrix acts as the subtrahend.
  4. Matrix Subtraction:
    • var resultMatrix = matrix.diff(matrixA, matrixB): Subtracts matrixB from matrixA using the matrix.diff() function. The result is stored in resultMatrix, which contains the element-wise difference between the two matrices.
  5. Table Creation and Display:
    • var displayTable = table.new(position.top_right, 1, 2, color.green): Creates a new table named displayTable positioned at the top right of the chart. The table is initialized with 1 column and 2 rows, with a green border color. The table is used to display the result of the matrix subtraction.
    • table.cell(displayTable, 0, 0, "Matrix A - Matrix B:"): Adds a cell to the first row of the table with the text “Matrix A – Matrix B:”, serving as a label for the result.
    • table.cell(displayTable, 0, 1, str.tostring(resultMatrix)): Converts the resultMatrix to a string using str.tostring() and displays this string in the second row of the table. This shows the outcome of the subtraction operation between matrixA and matrixB.

Difference Between a Matrix and a Scalar Value

//@version=5
indicator("`matrix.diff()` Example 2")

if barstate.islastconfirmedhistory
    var matrixX = matrix.new<float>(2, 3, 4) // Matrix X with 2x3 dimensions, filled with `4`.
    var scalarDiffResult = matrix.diff(matrixX, 1) // Resulting matrix after subtracting scalar `1` from Matrix X.
    
    var displayTable = table.new(position.top_right, 1, 2, color.green)
    table.cell(displayTable,  0, 0, "Matrix X - Scalar 1:")
    table.cell(displayTable,  0, 1, str.tostring(scalarDiffResult))
Difference Between a Matrix and a Scalar Value

Detailed Walkthrough

  1. Indicator Declaration: The script begins with //@version=5, indicating it uses Pine Script version 5. An indicator titled “matrix.diff() Example 2″ is declared, which sets the context for this example’s functionality.
  2. Conditional Execution: The if barstate.islastconfirmedhistory condition ensures the enclosed code block executes only once at the last confirmed historical bar. This approach optimizes script performance by avoiding unnecessary computations on every bar update.
  3. Matrix Initialization:
    • var matrixX = matrix.new<float>(2, 3, 4): A matrix named matrixX is created with dimensions of 2 rows and 3 columns. Each element in the matrix is initialized to the float value 4. This matrix serves as the base for the subtraction operation that follows.
  4. Subtracting a Scalar from the Matrix:
    • var scalarDiffResult = matrix.diff(matrixX, 1): The matrix.diff() function is used to subtract a scalar value of 1 from each element in matrixX. The result of this operation is stored in scalarDiffResult, which is another matrix representing the element-wise difference.
  5. Creating and Populating a Display Table:
    • var displayTable = table.new(position.top_right, 1, 2, color.green): A table for displaying the results is created with its position at the top right of the chart. The table has 1 column and 2 rows, with a green border color for aesthetic purposes.
    • table.cell(displayTable, 0, 0, "Matrix X - Scalar 1:"): The first cell in the table is populated with the text “Matrix X – Scalar 1:”, which serves as a descriptive label for the result being displayed.
    • table.cell(displayTable, 0, 1, str.tostring(scalarDiffResult)): The result of the subtraction (scalarDiffResult) is converted to a string using str.tostring() and displayed in the table’s second row. This visually presents the outcome of subtracting 1 from each element in matrixX.

Key Features and Takeaways

  • Functionality: The matrix.diff() function supports both matrix-to-matrix and matrix-to-scalar subtractions, offering flexibility in mathematical operations.
  • Syntax and Application: It has two overloads, accepting either two matrices or a matrix and a scalar value as arguments, making it versatile for different use cases.
  • Practical Use: This function is essential for data manipulation and analysis within Pine Script, especially when working with financial data or creating custom indicators and strategies.

Leave a Comment