Mathworks' demo:
- https://www.mathworks.com/matlabcentral/answers/94495-how-can-i-create-animated-gif-images-in-matlab
- https://www.mathworks.com/help/matlab/ref/imwrite.html#btv452g-1
Starting in Matlab R2022a, another option is to use exportgraphics with append=true. See this Community Highlight for an example.
Chad Greene's function on the file exchange: