Search code examples
matlabsimulink

How to summarize values of the attribute across all entities


In my model there are an entity generator, some attribute function(out_attrName) and an entity sink. How do I get the sum of all attrName values of every entity? I want to get the value of every entity before it gets to the sink and accumulates this value.

I tried to use a 'Cumulative Sum' block but no luck. This block requires discrete time on the input, so I use Discrete-Time Integrator. Can't say I use it in correct way: for example if values to sum are 34 and 40, the total sum can be some thing like 12344 instead of correct 74.

EDIT:

Example:
consider the following model: 10 entities go to the server and then to the sink.
There are 2 Set attribute blocks:

  • First one for StartTime (current time from Clock, before the server)
  • Second one for EndTime (current time from Clock, after the server)

One Attribute function block to set ServiceTime attribute = EndTime - StartTime.
The model is pretty simple, so ServiceTime attribute is always equal 10. We can see it on the Signal scope.
We've got 10 entities. In each entity there is an attribute ServiceTime == 10. Now I want to get sum of ServiceTime attributes for all entities. 10*10=100. How do I do that?


Details:

  1. Model
  2. Set attribute 1
  3. Server
  4. Set attribute 2 & Script function
  5. Get attribute

Solution

  • After some research here is my own answer that works for me.
    Please comment this answer if I wrong in some point.

    1. We need an accumulator (some storage) to store data. So we need to use MatLab work space for that. We can read/write values from it with functions coder.extrinsic('evalin') and coder.extrinsic('assignin').

    2. We have to put all values from all entities in single vector. After this operation we'll have data in one place and can do whatever we like to. This vector will be "hosted" by work space.

    3. In my case it's easy to assign vector elements by index. So there is an ID for every entity (it is the #d value from generator).

    4. Finally, lets write data to vector. Before starting the model, execute this code in Matlab:
      someVar = zeros(1000,1)

    Saving data in Attribute function block right before sink:

    out_EntityDuration = FinishTime - StartTime;
    
    coder.extrinsic('evalin');
    coder.extrinsic('assignin');
    
    x = zeros(1000,1);
    x = evalin('base', 'someVar');
    
    x(Id+1) = out_EntityDuration;
    
    assignin('base','someVar',x);
    

    See more about read/write to workspace here http://www.mathworks.com/matlabcentral/newsreader/view_thread/263578

    After execution the model someVar store data. Now we can find sum or average value.