Here's what I ended up doing:
I wrote the image as a png file in regular sRGB format and then used a command line tool to attach the color profile to the image:
imwrite(img, "test.png");
setenv('PATH', [getenv('PATH') ':/opt/homebrew/bin']);
system('exiftool -"icc_profile<=DisplayP3.icc" test.png');
Here /opt/homebrew/bin is where exiftool is installed on my mac and DisplayP3.icc is the color profile which I downloaded from ICC's website.