Using Matrix in a Loop

Hello Experts,

I intend to primarily figure out a dynamic band of price levels that changes at every bar in order to then discern a figure by calculating those levels. Using a matrix would be easier for my further calculations but I am stuck assigning values to the matrix and need your kind help.

OptSymStepMult = Param( "Upper-Lower Range", 10, 1, 100, 1 );

fvb = Status( "firstvisiblebar" );
lvbi = LastValue( BarIndex() );

UpperRangeOptSym = ...; //Formula to calculate the upper band limit
LowerRangeOptSym = ...; //Formula to calculate the lower band limit

RowNum = OptSymStepMult * 2; //Same as UpperRangeOptSym - LowerRangeOptSym
col = 0;
for( j = fvb; j <= lvbi - fvb + 1; j++ )
{
	 row = 0;
	 for( i = LowerRangeOptSym[ j ]; i <= UpperRangeOptSym[ j ]; i = i + lvStpDiff )
	 {
		 MtrxRecStrk = Matrix( RowNum, 3, 0 );
		 MtrxRecStrk[ row ][ col ] = i;
		 row++;
	 }
	 col++;
}

The error that I am getting is as follows:
Untitled

I am definitely doing something fundamentally wrong. Please help correct!

Thank you very much....

  1. Are you really sure that you need Matrix?

  2. As for creating matrix I doubt you need to use loop in your case. Simply use MxSetBlock() as you seem to want to store array blocks. Besides your loop looks awful. Remove it.

  3. In general: Matrix() is not supposed be used inside loop. Matrix() is set outside of loop.

2 Likes

You may have multiple issues, but let's start with some easy ones. Your matrix (which is probably defined in the wrong place, as @fxshrat pointed out) only has 3 columns:

 MtrxRecStrk = Matrix( RowNum, 3, 0 );

However, your loop is most likely incrementing your column index more than twice:

for( j = fvb; j <= lvbi - fvb + 1; j++ )
{
...
   ++col;
}

Therefore, you quickly get an index out of range error when col > 2.

2 Likes

Ahhh! back to work....

Ha ha ha.... Wanted to but did not know how to. Thanks for your help!

Doubt! So, basically we can insert an entire array onto a column or row of a matrix using MxSetBlock. Great! Purely awesome! Now let's say my concern is within the limits of Visible bars only, then how to dynamically deal with the size of the array?

Don't worry, if the number of visible bar changes, your formula will be re-executed, so new matrices will be created.

1 Like