Changing the location of the generated code is done solely through Simulink Preferences via Preferences Menu or Command Line. These parameters are set for a single session of MATLAB; i.e. closing and re-opening MATLAB should restore the default values.
The following documentation page explains the default behavior and impact of these preferences: Manage Build Process Folders- MATLAB & Simulink
(a) Changing the parameters using the MATLAB UI:
1. Navigate to Simulink Preferences. This menu will either be in your MATLAB toolstrip at the top under Preferences > Simulink Preferences or, prior R2019a, you can open a Simulink Model and select File > Simulink Preferences
2. Specify the two fields on right-hand pane:
- Simulation cache folder — root folder in which to place build artifacts used for simulation
- Code generation folder — root folder in which to place Simulink Coder code generation files
Here, you can specify any directory of your choosing. Note that all paths specified are added to the MATLAB path.
Please note that all Simulink Models will now use these settings for this MATLAB Session. So, if code is generated for two different models, it will use the exact same path specified here to store generated code.
(b) Using the command line:
The "Simulink.fileGenControl" command enables command-line manipulation of the same parameters: https://www.mathworks.com/help/simulink/slref/simulink.filegencontrol.html
The following lines:
cfg = Simulink.fileGenControl('getConfig');
cfg.CacheFolder = fullfile(eval(['pwd']),'generatedCache');
cfg.CodeGenFolder = fullfile(eval(['pwd']),'generatedCode');
Simulink.fileGenControl('setConfig', 'config', cfg,'createDir',true);
specify the current working directory, 'pwd', create two folders 'generatedCache' and 'generatedCode' in the current directory, and set these as the target folders for all code generation.
Setting these parameters using command line still changes the behavior for all Simulink Models during your MATLAB session. However, using the command line would be a convenient way to programmatically alter the CodeGenFolder and CacheFolder parameters if you wanted to change them for different models.
(c) Using Simulink Projects
When using Simulink Projects, you can set project-specific cache and code generation folders. See the following documentation page for more details:
Specify Project Details, Startup Folder, and Derived Files Folders- MATLAB & Simulink