Perform Element-Wise Operations on a GPU

This example shows how to perform element-wise, or pixel-based, operations on a GPU by using functions that send both the data and operations to the GPU for processing. This method is most effective for element-wise operations that require 2 or more data sets.

Move the data from the CPU to the GPU by creating a gpuArray object.

I = imread('concordaerial.png');
Igpu = gpuArray(I); 

Create a custom function that performs element-wise operations. This example creates a custom grayscale conversion function using weighted RGB data.

function gray = rgb2gray_custom(r,g,b)
gray = 0.5*r + 0.25*g + 0.25*b;

Perform the operation on the GPU. Use arrayfun to pass the handle to the custom function and data object to the GPU for evaluation.

Igray_gpu = arrayfun(@rgb2gray_custom,Igpu(:,:,1),Igpu (:,:,2),Igpu(:,:,3));

Move the data back to the CPU from the GPU, using the gather function.

I_gpuresult = gather(Igray_gpu);