MATLAB: I want to write an S function block to read/write from/to a CSV file. Could you give me a demo

simulink

.

Best Answer

Please find attached an example C-MEX S function that would rapidly read or write log data into a CSV file.
For the writeFile block:
This particular C MEX S Function uses a MEX file named 'writeFile.mexw64'. This would not work on your computer if you do not have a 64 bit windows machine running R2013a.
If you want to run this model on a newer or older version of MATLAB you would have to recompile the source files used to generate a new MEX S function.
1) First extract all the files in the ZIP file that is attached
2) Navigate to that folder in MATLAB. (Make it your current working directory).
3) Delete the old MEX file, and regenerate a new MEX file by typing in the following command into the MATLAB Command Window:
>>mex -g writeFile.c writeFile_wrapper.c
This would create a new MEX file.
Alternatively, you could rebuild the MEX file using the S function Builder blocks in the model.
4) Run the model toCustomer.mdl
You will see that the block 'writeFile' in the model requires inputs to be an array of 100 doubles.
I understand that this may not be the case for your model. If, for example, your model requrires an array of 12 int32s to be written every time step, you would have to edit the source files that I have included, and re-MEX the files again.
This is how you do it:
Open the model, and you should find the S function builder blocks for each of the corresponding S-functions. Make all the necessary changes that you want, and 'rebuild' the mex file by clicking on the Build button on the top right hand side of the S function Builder Dialog.
Related Question