opencl Kernel Basics Vectors in OpenCL

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


Each fundamental opencl type has a vector version. You can use the vector type by appending the number of desired components after the type. Supported number of components are 2,3,4,8 and 16. OpenCL 1.0 does not offer three components.

You can initialize any vector using two ways:

  • Provide a single scalar
  • Satisfy all components
float4 a = (float4)(1); //a = (1, 1, 1, 1)


float4 b = (float4)(1, 2, 3, 4);
float4 c = (float4)(1, (float3)(2));

or any other combination of vectors which satisfy the number of components. To access the elements of a vector you can use different methods. You can either use indexing:

a[0] = 2;

or use literals. The advantage of literals is that you can combine them any way you want, well do that in a moment. You can access all vector components with

a.s0 = 2; // same as a[0] = 2

you can also combine multiple components into a new vector

a.s02 = (float2)(0, 0); // same as  a[0] = 0; a[2] = 0; or even a.s20 = (float2)(0, 0)

you can change the order of the components in any way you want.

a.s1423 = a.s4132; // flip the vector

but you cannot do something like

a.s11 = ... // twice the same component is not possible

There are some convenient shorthands for accessing vector components. The following shorthands only apply to sizes 2, 4, 8 and 16

a.hi //=a.s23 for vectors of size 4, a.4567 for size 8 and so on.
a.lo //=a.s01
a.even //=a.s02
a.odd //=a.13

For vector sizes 2,3 and 4 there are some additional shorthands

a.x //=a.s0
a.y //=a.s1
a.z //=a.s2
a.w //=a.s3

Got any opencl Question?