Conditionally Execute a function

[Old posts from the commercial version of ArrayFire] Discussion of ArrayFire using CUDA or OpenCL.

Moderator: pavanky

Conditionally Execute a function

Postby anishk25 » Wed Jan 22, 2014 12:59 pm

Hi, I am trying to execute a function in ArrayFire inside a gfor loop only if a certain condition is met. I have tried several ways to do this but none of them were successful. Here is a simple example of what I tried to do

Code: Select all
array do_something(array i){
   return i;

int main(){
    array A = seq(1,100);   

    gfor(array i, 100){
         array condition = (A(i) % 5 == 0);
          array exec = condition && do_something(A(i)); // execute the function do_something only if A(i) is a multiple of 5
  return 0;

The above code prints all values contained in the array A. I thought with the operator &&, short circuiting applied. In other words if condition was 0 it will never even go to the second statement. Can someone please help me figure this out?
Posts: 4
Joined: Wed Dec 18, 2013 9:00 pm

Re: Conditionally Execute a function

Postby pavanky » Wed Jan 22, 2014 2:14 pm


arrays can contain multiple elements. There is no right way to short circuit an entire array (for example part of it may be true, part of it may be false).
What we do is short circuit based on each element inside the CUDA code. This would mean both expressions have to be evaluated first.

As for conditional execution inside gfor, this is not permitted. GFOR needs to do the same operations for all elements.

So for example if you are doing something like this.

Code: Select all
for (int i = 0; i < n; i++)
   if (i % 5 == 0) res(i) = do_something_1(i);
   else               res(i) = do_something_2(i);

it can be converted into GFOR code in the following manner.
Code: Select all
gfor (array ii, n) {
  array condition = (ii % 5 == 0);
  array true_part =  do_something_1(ii);
  array false_part = do_something_2(ii);
  // Do the masking
  res(ii) = condition * true_part + (1 - condition) * false_part;

This way all iterations of gfor do the same operation without divergence.
Pavan Yalamanchili,
~ If it is not broken, you have not tried hard enough ~
User avatar
Site Admin
Posts: 1123
Joined: Mon Mar 15, 2010 7:39 pm
Location: Atlanta, GA

Return to [archive-commercial] Programming & Development with ArrayFire