MATLAB: How to automatically limit the number of threads used by components built with MATLAB Compiler and MATLAB Builder products

MATLAB Builder EXMATLAB Builder NEMATLAB CompilerMATLAB Compiler SDK

In previous MATLAB versions, I was able to set the number of threads which were used by MATLAB in the Preferences menu. This setting would then automatically propagate to the components that I compile using MATLAB Compiler.
I have seen the maxNumCompThreads function, and I can easily use it in combination with standalone applications. However if I create a library, COM component, .NET assembly, or Java archive with multiple functions, I do not want to have to add maxNumCompThreads calls to all my functions or add a special initialization function which always needs to be called first.

Best Answer

Similar to the preferences which are propagated into your component, the files 'matlabrc.m' and 'startup.m' files are also included in the compilation. As in base/undeployed MATLAB, these functions are automatically run when you initialize your component.
To automatically set the number of threads used by your component, create a file named 'startup.m' in your project directory and add the following lines of code to it:
warning off MATLAB:maxNumCompThreads:Deprecated
maxNumCompThreads(1);
The first line of code suppresses the warning which is issued by calling maxNumCompThreads, and the second line actually sets the number of threads to 1.
NOTE: The maxNumCompThreads function will be removed in a future version of MATLAB. See the official function Help for more information:
https://www.mathworks.com/help/matlab/ref/maxnumcompthreads.html