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

Understanding matrix.concat() Function in Pine Script

Photo of author
Published on

This article delves into the matrix.concat() function, providing a comprehensive guide to its syntax, usage, and practical applications.

Syntax

The syntax for the matrix.concat() function is straightforward:

matrix.concat(id1, id2) → matrix<type>

Arguments

  • id1 (any matrix type): This is the matrix object into which another matrix will be concatenated.
  • id2 (any matrix type): This is the matrix object whose elements will be appended to id1.

Example

Let’s explore an example to understand how matrix.concat() works in practice.

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

// Create a 2x4 "int" matrix containing values `0`.
matrix1 = matrix.new<int>(2, 4, 0)
// Create a 2x4 "int" matrix containing values `1`.
matrix2 = matrix.new<int>(2, 4, 1)

// Append matrix `matrix2` to `matrix1`.
matrix.concat(matrix1, matrix2)

// Display matrix elements.
if barstate.islastconfirmedhistory
    var displayTable = table.new(position.top_right, 2, 2, color.green)
    table.cell(displayTable, 0, 0, "Matrix Elements:")
    table.cell(displayTable, 0, 1, str.tostring(matrix1))
Example

Walkthrough

  1. Indicator Declaration: The script begins with setting the version and declaring the indicator using indicator(), with a title that indicates what the example will demonstrate.
  2. Matrix Creation: Two matrices, matrix1 and matrix2, are created using matrix.new<int>(). matrix1 is initialized with zeros, and matrix2 with ones. Both matrices have dimensions of 2×4.
  3. Concatenation: The matrix.concat(matrix1, matrix2) function call appends matrix2 to matrix1, effectively altering matrix1 to contain the elements of both matrices.
  4. Displaying Results: The script uses table.new() and table.cell() functions to display the concatenated matrix’s elements on the chart, but only when the script is on the last confirmed historical bar (barstate.islastconfirmedhistory).

Key Features and Takeaways

  • Function Usability: matrix.concat() is used to append one matrix to another, which is particularly useful for data analysis and manipulation tasks that involve working with structured data in a matrix form.
  • Syntax and Application: The function requires two matrix-type arguments and returns a new matrix that combines the elements of both input matrices. This functionality can be leveraged to dynamically adjust data structures in response to changing market conditions or for complex calculations.
  • Practical Use Cases: In trading strategies or indicators, concatenating matrices can be essential for tasks like combining different datasets, extending historical data ranges, or managing multi-dimensional data arrays for complex calculations.

Leave a Comment