Running counters using S-functions

Hello,
I am designing an autopilot waypoint tracking system. I have a list of waypoints. The autopilot is given the first as a reference waypoint and when the aircraft gets a distance D close to the waypoint, I want the reference to change to the next waypoint. I did this by having a flag based on whether the aircraft is D distance close to the waypoint or not (1 if it is and 0 if it is not). The flag increments a counter which keeps track of which waypoint is currently the reference.
I learned (the hard way) that variables passed to workspace during the simulation are not available until after the simulation and the only way to have a running counter would be through S-functions.
The question I have is: How can I (can I even?) build a simple S-function that increments a fixed counter based on a flag input and then outputs the value of the fixed counter (which will be used to determine the current waypoint)? I've been using the S-function builder but I'm not sure how to reference a static/global/base-workspace variable (I'm not too familiar with C either).
Any help would be tremendously appreciated.
~ IH

 채택된 답변

Kaustubha Govind
Kaustubha Govind 2011년 6월 8일

0 개 추천

If this is all you want your S-function to do, then you can simply implement your own subsystem (using a unit delay block to store the counter's state) or use an Embedded MATLAB Fcn block containing code to the effect of:
function y = fcn(u)
%#codegen
persistent counter;
if isempty(counter)
counter = 0; %initialize
end
if (u == 1) %implement this condition as per your requirement
counter = counter + 1;
end
y = counter;
Is there a reason you chose to use a C-MEX S-function instead? (By the way, I would recommend Level-2 MATLAB file S-functions or Embedded MATLAB Functions if you are not comfortable with C/C++ and need to perform simple enough operations)

댓글 수: 1

Ismail Hameduddin
Ismail Hameduddin 2011년 6월 9일
Great, thanks! I managed to make it work (for the most part) using a variation of the above. I didn't know of the existence/validity of the persistent command in Simulink.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Block and Blockset Authoring에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by