In this article, you will learn to write information from your model in a text file using the MATLAB command fprintf.
Let’s say you have a model that you want to check because there have been modifications to it, and you need to make sure it runs. It would be nice to be able to check if the model is running and write the results in a text document automatically so that every time you want to know, you can just run this script. (If you don’t care about the explanation, the script is at the end of this article.)
Assuming you have the following model:
First, let’s check if the model can run:
modelName = 'myVerySimpleModel'; open(modelName); try sim([modelName '.slx']) modelRun = 1; catch modelRun = 0; end
The sim command is explained here.
Here, we are running the Simulink model. If it runs modelRun is 1. If it generates an error, modelRun is 0.
Then, we can close the model and write the results in a .txt document.
modelName = 'myVerySimpleModel'; open(modelName); try sim([modelName '.slx']) modelRun = 1; catch modelRun = 0; end close_system(modelName) % open the file textFileName = 'checkReport.txt'; fid = fopen(textFileName, 'at'); if modelRun % \n is to go to the next line fprintf(fid, 'The model runs.\n'); else % char(39) is used as a single quotation mark fprintf(fid, ['The model doesn' char(39) 't run.\n']); end % close the file fclose(fid);
Let’s examine how we wrote content:
- We use the fopen MATLAB command to open the file (‘a’ is for appending data to the end of the file, and ‘t’ is for opening the file in text mode).
- We write the content using the fprintf MATLAB command.
- We close the file using the fclose MATLAB command.
After running this script, a file named “checkReport.txt” is generated:
Let’s add an undefined variable “x” as the simulation time to generate an error:
Finally, after running the script again, we get: