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

Understanding the matrix.col() Function in Pine Script

Photo of author
Published on

The matrix.col() function is a powerful tool in Pine Script designed for working with matrices, a structure that allows you to organize data in rows and columns. This function specifically extracts a column from a given matrix and returns it as a one-dimensional array. Below, we delve into the syntax, usage, and application of this function to enhance your scripting in trading strategies or indicators on the TradingView platform.


The syntax for matrix.col() is straightforward:

matrix.col(id, column) → array<type>
  • id: This argument takes any matrix type and represents the matrix object from which you wish to extract a column.
  • column: A series int indicating the index of the column you want to extract. Remember, indexing in Pine Script starts at 0.


Let’s break down the provided example to understand its components:

indicator("`matrix.col()` Example", "", true)

// Create a 2x3 "float" matrix from `hlc3` values.
matrixM = matrix.new<float>(2, 3, hlc3)

// Return an array with the values of the first column of matrix `matrixM`.
arrayA = matrix.col(matrixM, 0)

// Plot the first value from the array `arrayA`.
plot(array.get(arrayA, 0))

Detailed Walkthrough

  1. Indicator Declaration: Initializes an indicator script with a custom title. This is essential for any script running on TradingView.
  2. Matrix Creation: A matrix named matrixM is created using matrix.new<float>(2, 3, hlc3). This matrix is of type float and is 2×3 in dimension, filled with hlc3 values (the average of high, low, and close prices).
  3. Column Extraction: The function matrix.col(matrixM, 0) extracts the first column (index 0) of matrixM and stores it in arrayA.
  4. Plotting: Finally, plot(array.get(arrayA, 0)) plots the first value of arrayA on the chart. This demonstrates how you can access and utilize individual elements from the extracted column.

Key Features and Takeaways

  • Functionality: matrix.col() enables the extraction of specific column data from a matrix, which is particularly useful for analysis or manipulation of financial data in a structured form.
  • Syntax and Application: Understanding the syntax is crucial for correctly applying this function. The column index starts at 0, aligning with Pine Script’s zero-based indexing.
  • Flexibility: This function is adaptable to various types of matrices (e.g., float, int), making it versatile for different data manipulation needs in your scripts.
  • Utility in Trading Strategies: Extracting column data can be instrumental in calculating indicators or signals based on specific columns of data, offering a structured approach to handling complex data sets.

Leave a Comment