user3536870
user3536870

Reputation: 249

Matlab how to group time ranges

I have the following times

1.1
1.15
1.19
1.32
1.69
2.12
2.36
2.86
3.25
3.67
3.77
3.91
...

And I would like MALTAB to read the times and store the numbers into arrays where array 1 would be for times in 1-2 seconds. Array 2 would be 2-3 seconds and so on.

Thanks in advance for any help/advice given

Upvotes: 0

Views: 95

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112699

Let t denote your input vector. Then

t = sort(t); %// not needed if t is assured to be non-decreasing (as in the example)
result = mat2cell(t(:), diff([0; find(diff([floor(t(:)); NaN]))]));

In your example, this gives

result{1} =
    1.1000
    1.1500
    1.1900
    1.3200
    1.6900
result{2} =
    2.1200
    2.3600
    2.8600
result{3} =
    3.2500
    3.6700
    3.7700
    3.9100

Upvotes: 1

Divakar
Divakar

Reputation: 221584

You could use accumarray to have those arrays stored as cells of a cell array, like so -

groups = accumarray(floor(timeseries),timeseries,[],@(x){x})

Sample run -

>> timeseries
timeseries =
          1.1
         1.15
         1.19
         1.32
         1.69
         2.12
         2.36
         2.86
         3.25
         3.67
         3.77
         3.91
>> groups = accumarray(floor(timeseries),timeseries,[],@(x){x});
>> celldisp(groups)  %// Display cells of output
groups{1} =
          1.1
         1.15
         1.19
         1.32
         1.69
groups{2} =
         2.12
         2.36
         2.86
groups{3} =
         3.25
         3.67
         3.77
         3.91

Upvotes: 5

Jan van der Vegt
Jan van der Vegt

Reputation: 1511

I don't know the exact syntax for Matlab but an approach would be to use a floor function on the time variable which will map them to the integer part of your time, then put the ones with the same floor in the same array.

Upvotes: 0

Related Questions