MATLAB: How to edit the generated code to save output to TXT file

codecodegencustomEmbedded Coderfilematoutputsavetext;timetxtvalues

I have modified the Configuration Parameters -> Custom Code to save the outputs to a text file like this:
#include <stdio.h>
FILE * pFile;
pFile = fopen ("myfile.txt","w");
fprintf(pFile,"%f \n", myModel_Y.Out1 );
fclose (pFile);
This just gives me the last value of the Simulation. Is there a simple way to save all values (including the time values)?

Best Answer

Implementing the above code by adding it to Configuration Parameters, you will only see the last output. This is the expected behavior as the model executes in real time; therefore, when the model terminates, it actually has only the last data to throw out to the TXT file. There are many ways to achieve this, and one possible (and simplest) way is to modify the generated code instead of having it included in the Custom Code section.
An example model is attached and below is a procedure to achieve this workflow. You will have to generate the code yourself because it is compiler dependent. However, I am also attaching a .C file that was generated by Simulink Coder to which I made the changes in order to save the time and output values to a TXT File.
Here are the steps you need to follow:
1. Open the model custom_code_example.slx. It's a simple model that adds a noise to a sine wave. Run the model and see the output on scope. Do not make any changes to Configuration Parameters, but notice that the Custom Code section is empty.
<Output of the Scope>
2. Go ahead and build the Model to generate code. This will create a new folder "code_gen_example_grt_rtw". Go into this folder and notice 3 files that we would be using:
  •     code_gen_example.c - We will modify this file
  •     code_gen_example.bat - We will execute this batch file to update our modified C file above.
  •     code_gen_example.exe - This will be created by the BAT file above.
I have attached the modified code_gen_example.c file with the changes made that I will describe in the next step. This file is for your reference only. You would need to make similar changes to the C file generated by your compiler. 
3. Open the code_gen_example.c file and notice that I have added the #include "stdio.h" at Line 19 and a global file pointer File *pFile the top of the C file.
4. Now notice line 158 - 160 in attached C file. Here I have added the following code:
// Open a Text file for writing
printf("\n\nOpening Text File\n\n");
pFile = fopen ("myfile.txt","w");
Notice that this is in the code_gen_example_initialize function. The <model_name>_initialize function is called once when the model is loaded into memory. Here we are just opening the text file.
5. Similarly, when the model terminates or finishes executing, we need to close the TXT File. For this, I have added the following code in line 358-359 of code_gen_example_terminate function.
printf("\n\nClosing Text File\n\n");
fclose(pFile);
6. Next, we need to save the time and output values every time step the model executes. The C-function that is called to calculate the outputs is code_gen_example_step. In this function, notice that I added the following code at line 97 to save the time and output values to the TXT file:
fprintf(pFile,"%f, %f\n",code_gen_example_M->Timing.t[0],code_gen_example_Y.Out1 );
7. Now since the C-code is modified, we need to build the model EXE again to reflect these changes. To do so, we will execute the BAT file in the shell. Execute the following command in MATLAB Command Window to remake all the files
>> !code_gen_example.bat
This will build the new code_gen_example.exe file in the current folder. The following would be displayed on Command Window:
### Creating standalone executable "..\code_gen_example.exe" ... 
    link /RELEASE  /INCREMENTAL:NO /NOLOGO -subsystem:console,5.02 kernel32.lib  ws2_32.lib mswsock.lib advapi32.lib -out:..\code_gen_example.exe @code_gen_example.lnk rt_main.obj   
### Created: ..\code_gen_example.exe 
### Successfully generated all binary outputs. 
8. Now, let's go ahead and run this executable by executing the following command in MATLAB Command Window:
>>  !code_gen_example.exe
** starting the model ** 
Opening Text File 
** created code_gen_example.mat ** 
Closing Text File
This will create the text file myfile.txt in the current directory. This text file will contain the time and output values. To test we are getting the right output and compare the results of generated code to the model run in Simulink, try the following commands:
>> data = csvread('myfile.txt');
>> plot(data(:,1),data(:,2))
The plots might look slightly different because the model uses a random number generator, but you should see a sine wave with added noise similar to the output of Scope block in the model.
<Output in TXT file when model is run by the generated EXE>