%% Use MATLAB Functions with a GPU
% This example shows how to use GPU-enabled MATLAB functions to operate with gpuArrays. You can check the properties of your GPU using the gpuDevice function.

gpuDevice

% Create a row vector that repeats values from -15 to 15. To transfer it to the GPU and create a gpuArray, use the gpuArray function.

X = [-15:15 0 -15:15 0 -15:15];
gpuX = gpuArray(X);
whos gpuX

% To operate with gpuArrays, use any GPU-enabled MATLAB function. MATLAB automatically runs calculations on the GPU. For more information, see Run MATLAB Functions on a GPU. For example, use a combination of diag, expm, mod, round, abs, and fliplr.

gpuE = expm(diag(gpuX,-1)) * expm(diag(gpuX,1));
gpuM = mod(round(abs(gpuE)),2);
gpuF = gpuM + fliplr(gpuM);

% Plot the results.

imagesc(gpuF);
colormap(flip(gray));

% If you need to transfer the data back from the GPU, use gather. Gathering back to the CPU can be costly, and is generally not necessary unless you need to use your result with functions that do not support gpuArray.

result = gather(gpuF);
whos result

% In general there can be differences in the results if you run the code on the CPU, due to numerical precision and algorithmic differences between GPU and CPU. Answers on CPU and GPU are both equally valid floating point approximations to the true analytical result, having been subjected to different roundoff during computation. In this example, the results are integers and round eliminates the roundoff errors.
% Copyright 2019 The MathWorks, Inc.