GPU and CPU code: How to do?

Nycholas Maia · Mar 29, 2022 · 2K views
Question
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 PhD Expert
Answered Aug 13, 2026

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.'
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!