t=Tiff('Stacked.tiff','w');
tagstruct.ImageLength = y1; % image height
tagstruct.ImageWidth = x1; % image width
tagstruct.Photometric = Tiff.Photometric.RGB; % https://de.mathworks.com/help/matlab/ref/tiff.html
tagstruct.BitsPerSample = 8;
tagstruct.SamplesPerPixel = 3;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky; % groups rgb values into a single pixel instead of saving each channel separately for a tiff image
tagstruct.Software = 'MATLAB';
setTag(t,tagstruct)
write(t,squeeze(im2uint8(Imagelayer1)));
writeDirectory(t);
setTag(t,tagstruct)
write(t,squeeze(im2uint8(Imagelayer2))) %%%appends the next layer to the same file t
% do this for as many as you need, or put it in a loop if you can
close(t) %%% this is necessary otherwise you won't be able to open it in imageJ etc to double check, unless you close matlab