Using Vector Code rather than loop code

Hi everyone

I am trying to create an array which stores last green candle close value as it occurs. I am able to perfectly achieve this using loop with below code

LastGreenClose = 0;
for( i = 15; i < BarCount; i++ )
{
	if(C[i] > O[i]) 
		LastGreenClose[i] = C[i];
	else
		LastGreenClose[i] = LastGreenClose[i-1];
}

However, I am looking for a more AFL way of doing this using vector processing, as I believe it will be atleast 10X faster. I am trying the following code but it gives undesired result

LastGreenCLose = IIf(C>O, C, Ref(LastGreenCLose, -1);

I know the above line won't work because Ref(x, -1) will just create a new array first, while I am trying to use this array in a recursive sense (created bar by bar sense as in the loop).

Please help me with a vectorised code for achieving the same result as the loop code.
Thanks in advance.

Search for ValueWhen function. It does what you need.

There are literally dozens of posts that already cover what you asked for, example:

and

and

http://www.amibroker.com/kb/2014/09/29/debugging-techniques-part-1-exploration/

and ValueWhen will be something like 30-50x faster than loop. Your loop can be replaced by single function call that not only is shorter but also much cleaner than loop and reads like plain English sentence:

"give me the VALUE of Close WHEN Close was higher than Open"

LastGreenCLose = ValueWhen( C > O, C ); // that is easy and straightforward one-liner

So array code is actually easier to write than looping code if you just stop thinking in "obsolete" looping terms and starting thinking on the concept level (what this code actually does).

6 Likes