Can Arrays be paired to run operations without the need for loops?

 

I am just beginning to learn MQL5, and wonder if I can get your help with a problem I encounter.

Lets consider an example in which I want to calculate the median price of the last 10 days, I collect one array of the low  prices and other for the high prices of the last 10 days.

One could loop over each day in both arrays adding the two values on each array at position i and then dividing them by 2.

However, I think a much more efficient way would be to simply add array 1 and array 2 and divide them by 2. Looking at the information about matrices and vectors, this should be possible, but when I do it. I get a "Invalid array access" error.


double High[];
double Low[];  
double HL2[];

CopyHigh("XAUUSD",PERIOD_D1,0,Length,High);
CopyLow("XAUUSD",PERIOD_D1,0,Length,Low);

HL2= (High + Low)/2;
Matrix and Vector operations in MQL5
Matrix and Vector operations in MQL5
  • www.mql5.com
Matrices and vectors have been introduced in MQL5 for efficient operations with mathematical solutions. The new types offer built-in methods for creating concise and understandable code that is close to mathematical notation. Arrays provide extensive capabilities, but there are many cases in which matrices are much more efficient.
 
Camilo Mora:

I am just beginning to learn MQL5, and wonder if I can get your help with a problem I encounter.

Lets consider an example in which I want to calculate the median price of the last 10 days, I collect one array of the low  prices and other for the high prices of the last 10 days.

One could loop over each day in both arrays adding the two values on each array at position i and then dividing them by 2.

However, I think a much more efficient way would be to simply add array 1 and array 2 and divide them by 2. Looking at the information about matrices and vectors, this should be possible, but when I do it. I get a "Invalid array access" error.

An "array" is not a "vector". You have to declare the variable as a vector and then use the specialised version of the CopyRates function for copying the highs and lows into the vectors.

Please reference the following ... Documentation on MQL5: Matrix and Vector Methods / Initialization / CopyRates

 

Thank you Fernando, that was very useful... here is the code I came out with, which does what I wanted... thanks again..


int Length = 7;


vector High;
vector Low;
vector HL2;
vector Returns;
double Volatility;

High.CopyRates("XAUUSD",PERIOD_D1, COPY_RATES_HIGH,  1, Length);
Low.CopyRates("XAUUSD", PERIOD_D1,COPY_RATES_LOW,  1, Length);

HL2=(High+Low)/2;

Returns=(High-Low)/HL2*100;

Volatility= Returns.Median();
Print(Volatility);