GPU and CPU code: How to do?

Illustration
Nycholas Maia - 2022-03-29T09:05:01+00:00
Question: GPU and CPU code: How to do?

I would like to share my MATLAB project with others that does not have any GPU card in your computers, but I want to use the GPU power in my computer.   How can I write ONLY ONE MATLAB code that can be run with and without GPU system?   My main GPU commands are: parfor GPUarray In C/C++ language, we can write a pre-processor that can be this "magic shift". Is possible to do this in MATLAB?  

Expert Answer

Profile picture of John Michell John Michell answered . 2025-11-20

Yes, you can write MATLAB code that can run on systems with and without a GPU by using conditional checks and fallback mechanisms. Here's a step-by-step approach to achieve this:

  1. Check for GPU Availability: Use the gpuDeviceCount function to check if a GPU is available.

  2. Conditional Code Execution: Use if-else statements to run GPU-specific commands if a GPU is available, and CPU-specific commands otherwise.

Example Code:

Here's a simple example illustrating how you can write your MATLAB code to run with and without a GPU:

matlab
% Check for GPU availability
gpuAvailable = gpuDeviceCount > 0;

if gpuAvailable
    disp('GPU is available. Running on GPU.');
else
    disp('GPU is not available. Running on CPU.');
end

% Define some example data
n = 1e6;
A = rand(n, 1);

% Use GPU if available, otherwise use CPU
if gpuAvailable
    % Transfer data to GPU
    A = gpuArray(A);
    
    % Use parfor loop with GPU
    parfor i = 1:length(A)
        A(i) = A(i) * 2;
    end
    
    % Gather data back to CPU
    A = gather(A);
else
    % Use parfor loop on CPU
    parfor i = 1:length(A)
        A(i) = A(i) * 2;
    end
end

disp('Processing completed.'


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!