3.66667

3.7 | 3 ratings Rate this file 4 Downloads (last 30 days) File Size: 9.22 KB File ID: #13438

File I/O C S-function Example

by Jarrod Rivituso

 

18 Dec 2006 (Updated 18 Dec 2006)

A simple C S-function which reads data from a file during simulation.

| Watch this File

File Information
Description

S-functions are used to create user defined blocks in Simulink. This S-function creates a block that reads data from a file incrementally at each time step of the Simulink simulation.

The S-function was written in C and uses the standard file I/O functions from the stdio.h library (fopen, fscanf, fclose). It is intended merely as an example.

The trickiest part of writing S-functions can sometimes be maintaining persistent data in subsequent calls to the S-function. This issue presents itself in this example. In order to read from the file throughout the simulation without closing and reopening the file each time step, the FILE pointer is stored in the PWork vector. This gives the S-function access to the FILE pointer at each step in the simulation.

In this S-function, the mdlStart function opens the file at the start of the simulation and the mdlTerminate function closes the file at the end. The mdlOutputs function is used to read data from the file at every time step.

To run the example:
1) Enter
mex -setup
at the MATLAB Command Prompt and select a compiler
2) Copy the attached files to the current MATLAB directory
3) Enter
mex cfileiosfun.c
to compile the S-function
4) Open the attached model and simulate.

Required Products Simulink
MATLAB release MATLAB 7.3 (R2006b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
29 Dec 2006 sae Yong Lee

Good as an example for s-function beginers

11 Jan 2008 Deepa Jain  
12 Sep 2008 H. Grutzeck

Unfortunately c-Code has poor documentation.
So its difficult for beginners to understand
whats happening

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
data import Jarrod Rivituso 22 Oct 2008 08:53:12
data export Jarrod Rivituso 22 Oct 2008 08:53:12
sfunction Cristina McIntire 06 Feb 2009 11:26:57
mex Cristina McIntire 06 Feb 2009 11:26:57
c Cristina McIntire 06 Feb 2009 11:26:57
fscanf Cristina McIntire 06 Feb 2009 11:26:57
input Cristina McIntire 06 Feb 2009 11:26:57
output Cristina McIntire 06 Feb 2009 11:26:57
stdioh Cristina McIntire 06 Feb 2009 11:26:57
cmex Cristina McIntire 06 Feb 2009 11:26:57
data import qingjun 14 Oct 2011 17:33:43

Contact us at files@mathworks.com