Code covered by the BSD License  

Highlights from
Time Logger for Stateflow

image thumbnail

Time Logger for Stateflow

by

 

This function will log the time each state was active during simulation.

Stateflow_Time_Logger(mdlName)
function Stateflow_Time_Logger(mdlName)
% This function will run a Simulink model that contains Stateflow charts.
% It will time how long each state was active and display it in a table.
%
% Inputs: Model Name - mdlName
% Outputs: Table
%
% Example use: Stateflow_Time_Logger('example_sf_car')
%
% Created by Roni Peer, February 2013
%

mdl = mdlName;
bdclose all;
open(mdl);
rt = sfroot;
allStates = rt.find('-isa','Stateflow.State');
Names = cell(1,length(allStates));
remstr = allStates(1).Path;
tEnd = str2double(get_param(mdl,'StopTime'));

% Make sure simulation doesn't run forever:
if isinf(tEnd)
    tEnd = 1000;
    set_param(mdl,'StopTime',num2str(tEnd));
end

% Turn On data logging for each state:
for i = 1:length(allStates)
    allStates(i).LoggingInfo.DataLogging = 1;
    tempName = [allStates(i).Path '.' allStates(i).Name];
    % Remove model name from path:
    for j = 1:length(remstr)+1
        tempName(1) = [];
    end
    tempName(strfind(tempName,'/')) = '.'; % Replace chars with '.'
    Names{i} = tempName;
end
% Use DataSet format, and store in a specific name:
set_param(mdl,'SignalLogging','on');
set_param(mdl,'SignalLoggingName','sigsOut');
set_param(bdroot,'SignalLoggingSaveFormat','Dataset');

% Run model and collect results:
sim(mdl);

% Accumulate the  results:
resultsVec = cell(length(Names),2);
for i = 1:length(Names)
    A = sigsOut.getElement(Names{i});
    resultsVec{i,1} = A.Name;
    val = A.Values;
    val = addsample(val,'Time',tEnd,'Data',val.Data(end));
    try
        val = resample(val,(0:0.01:tEnd),'zoh');
    catch
        val.Data = zeros(size(0:0.01:tEnd));
    end
    resultsVec{i,2} = sum(val.Data)/length(val.Data)*tEnd;
end

% Display Time and State Name in Table:
figure('Name','Time results for State Machine');
uitable('Data', resultsVec,...
    'ColumnName',{'State','Time'},'Units','normalized',...
    'ColumnWidth',{150,50}, 'FontUnits','normalized');

% Not Needed for a function:
% clear allStates A val resultsVec tempName Names remstr tEnd i j mdl rt

Contact us