MQL4|Using Multidimensional Arrays in MetaTrader 4 (MT4)

In MQL4 programming for MetaTrader 4 (MT4), multidimensional arrays can be used to manage data in rows and columns. This article will explain the basics of using multidimensional arrays in a way that is easy for beginners to understand. Specifically, we will focus on two-dimensional arrays as examples.

What Are Multidimensional Arrays?

Multidimensional arrays are arrays with multiple dimensions. For example, a two-dimensional array manages data in rows and columns and can be treated similarly to tables in Excel. It is also possible to increase the dimensions to three, four, and beyond. The basic concept remains the same.

Basic Syntax of Two-Dimensional Arrays

The following sample code demonstrates the basic usage of two-dimensional arrays.

// Declaration of a two-dimensional array
double matrix[3][2];

// Assigning values to the two-dimensional array
matrix[0][0] = 1.0;
matrix[0][1] = 2.0;
matrix[1][0] = 3.0;
matrix[1][1] = 4.0;
matrix[2][0] = 5.0;
matrix[2][1] = 6.0;

// Displaying the contents of the two-dimensional array
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        Print("matrix[" + i + "][" + j + "] = " + matrix[i][j]);
    }
}
Execution Result

When this sample code is executed, the following results will be displayed.

matrix[0][0] = 1.0
matrix[0][1] = 2.0
matrix[1][0] = 3.0
matrix[1][1] = 4.0
matrix[2][0] = 5.0
matrix[2][1] = 6.0

Basic Operations of Multidimensional Arrays

Declaring Multidimensional Arrays

Before using multidimensional arrays, you need to declare the array. Specify the data type and the size of each dimension.

double matrix[3][2];  // Declaring a two-dimensional array of size 3x2
Assigning Values to Multidimensional Arrays

You assign values to each element of a multidimensional array using indexes. The indexes start from 0 for each dimension and go up to the specified size minus one.

matrix[0][0] = 1.0;
matrix[0][1] = 2.0;
matrix[1][0] = 3.0;
matrix[1][1] = 4.0;
matrix[2][0] = 5.0;
matrix[2][1] = 6.0;
Retrieving Values from Multidimensional Arrays

When retrieving values from a multidimensional array, use the indexes. The following code demonstrates displaying array values using nested loops.

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 2; j++) {
        Print("matrix[" + i + "][" + j + "] = " + matrix[i][j]);
    }
}

Summary

By using multidimensional arrays, you can efficiently manage and manipulate data within MQL4 programs. Understanding the basic usage of two-dimensional arrays allows you to handle more complex data structures. Beginners should start by learning the basic operations of multidimensional arrays and applying them to their actual trading programs.