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:
-
Check for GPU Availability: Use the
gpuDeviceCountfunction to check if a GPU is available. -
Conditional Code Execution: Use
if-elsestatements 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:
% 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.'
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.
Explore similar technical troubleshooting questions and verified MATLAB solutions: