Use FFT2 on the GPU to Simulate Diffraction Patterns
R2026bThis example uses Parallel Computing Toolbox™ to perform a two-dimensional Fast Fourier Transform (FFT) on a GPU.
In optics, you can use Fourier transform to approximate the far-field diffraction pattern produced by a plane wave incident on a small aperture [1]. These diffraction patterns are observed when a monochromatic light source passes through a small aperture, such as in Young's double-slit experiment.
You can speed up your code by running MATLAB® functions on a GPU. Many functions in MATLAB and other toolboxes run automatically on a GPU if you supply a gpuArray data argument. A gpuArray in MATLAB represents an array that is stored on the GPU.
Define Optical Mask
Before calculating the diffraction pattern, first define an optical with a small rectangular aperture.
Define a 2048-by-2048 mask. To ensure that all of the subsequent calculations are performed on the GPU, convert the mask to a gpuArray.
n = 2048; x = -n/2:1:n/2-1; [X,Y] = meshgrid(x); X = gpuArray(X); Y = gpuArray(Y);
Create a small rectangular aperture in the center of the mask.
aperture = (abs(X)<4) .* (abs(Y)<2);
Display the aperture.
figure imagesc(aperture) title("Rectangular Aperture") axis("off","equal") xlim([n/2-30 n/2+30]) ylim([n/2-30 n/2+30])

Simulate Diffraction Pattern
Simulate the effect of passing a plane wave through a small rectangular aperture. The two-dimensional Fourier transform describes the optical field in the far-field regime.
Calculate the two-dimensional Fourier transform using the fft2 function.
lightSource = double(aperture); farFieldSignal = fft2(lightSource);
Calculate and display the far-field optical field from the magnitude squared of the light field. Use the fftshift to rearrange the output so that the zero-frequency component is at the center.
farFieldIntensity = abs(farFieldSignal).^2; figure imagesc(fftshift(farFieldIntensity)) axis("off","equal") title("Rectangular Aperture Far-Field Diffraction Pattern")

Simulate Young's Double-Slit Experiment
One of the most famous experiments in optics is Young's double-slit experiment which shows light interference when an aperture comprises two parallel slits. A series of bright regions are visible where constructive interference takes place.
Define the aperture representing two slits.
aperture = ((abs(X)<=10).*(abs(X)>=8) ) .* (abs(Y)<20);
Display the aperture.
figure imagesc(aperture) title("Double Slit Arrangement") axis("off","equal") xlim([n/2-30 n/2+30]) ylim([n/2-30 n/2+30])

farFieldSignal = fft2(aperture);
Calculate and display the far-field optical field.
farfieldIntensity = abs(farFieldSignal).^2; imagesc(fftshift(farfieldIntensity)); axis("equal"); axis("off"); title("Double Slit Far-Field Diffraction Pattern");

References
[1] Fowles, G. R. Introduction to Modern Optics. New York: Dover, 1989.