More efficient way to convert this function to return array instead of single value

Hi AFL experts,

I have the following function which returns a single value.

function getVolumeHigh_excludeUpBars(period)
{
	volume_exclude_up = IIf( ROC(CLOSE,1) < 0, Volume, 0);
	
	SELECTED_BAR = SelectedValue( BarIndex() );
	volume_exclude_up[SELECTED_BAR] = Volume[SELECTED_BAR];	
	
	volume_High = hhv(volume_exclude_up, period);
	return volume_High;
}

I want to convert the above function to return an array instead of a single value. I rewrote the function. Here it is;

function getArray_VolumeHigh_excludeUpBars(period)
{
	volume_exclude_up = IIf( ROC(CLOSE,1) < 0, Volume, 0);
	
	for (i=(BAR_COUNT-1);i>=0;i--)
	{
		volume_exclude_up[i] = Volume[i];	
		volume_High[i] = hhv(volume_exclude_up, period);
	}	

	return volume_High;
}

The rewritten function is efficient as it uses for-do loop to assign value individually into the array. Is there a more efficient and elegant way to rewrite the function?

Thank you.

Your loop is not efficient at all and it is incorrect. You should not place array functions within barcount loop. Besides to calculate HHV_Volume on ROC < 0 there is not any loop required.

function getVolumeHigh_excludeUpBars(period)
{
	/// @link https://forum.amibroker.com/t/more-efficient-way-to-convert-this-function-to-return-array-instead-of-single-value/12295/2
	/// by fxshrat@gmail.com to user thankyou18
	local cond, volume_comp, volume_high, volume_exp;
	cond = ROC(C, 1) < 0;
	volume_comp = SparseCompress(cond, Volume);
	volume_high = HHV(volume_comp, period);
	volume_exp = SparseExpand(cond, volume_high);
	return ValueWhen(cond, volume_exp);
}

period = 20;

Plot( getVolumeHigh_excludeUpBars(period), "getVolumeHigh_excludeUpBars", colorRed );
5 Likes

Thank you very much, fxshrat. I always can count on you for the rescue. Haha.

There was a typo in my original post. I should have written inefficient, not efficient. Can't edit it now because edit time permitted has elapsed.