MATLAB Answers

Recursive concatenation of cell arrays

17 views (last 30 days)
LG
LG on 20 Jan 2015
Edited: Stephen on 21 Jan 2015
Hello,
I have a cell array, let’s call it Events_ext. Each cell is an event, containing time stamps in sec (6.037 = 6sec 37msec). The length of these events vary. By processing Events_ext I would like to create a new cell array (Events_ext2) in which all those consecutive cells from Events_ext get concatenated, where the time difference between the last member of one event and the first member of the consecutive event is less than 100ms. It should do it recursively.
For example, let’s say we have 10 events in the cell array:
A B C D E F G H I J
The time difference between the last timestamp in B and the first timestamp in C is less than 100ms. In addition, the time difference between the last timestamp in E and the first timestamp in F is less than 100ms. Also, the time difference between the last timestamp in F and the first timestamp in G is less than 100ms.
How to write the algorithm that creates
A (B+C) D (E+F+G) H I J , therefore creating 7 events out of the original 10?

Accepted Answer

Sara
Sara on 20 Jan 2015
Events_ext2 = Events_ext;
i = 0;
while i < numel(Events_ext2)-1
i = i + 1;
if(Events_ext2{i+1}(1)-Events_ext2{i}(end) < 100)
Events_ext2{i} = [Events_ext2{i} Events_ext2{i+1}];
Events_ext2(i+1) = [];
i = i - 1;
end
end
  1 Comment
LG
LG on 21 Jan 2015
Thank you!!! It works perfectly. The time should be written in ms, so the <100 condition has to be replaced with <0.1.

Sign in to comment.

More Answers (1)

Stephen
Stephen on 21 Jan 2015
Edited: Stephen on 21 Jan 2015
A fully vectorized version (without using any loops) in just three lines of code:
>> A = {[0,1],[2,3,4],[4.05,6,7,8],[9],[10,11],[11.05,13],[13.05,15],[16,17],[18,19,20],[21,22,23]};
>> B = (cellfun(@(v)v(1),A(2:end)) - cellfun(@(v)v(end),A(1:end-1))) < 0.1;
>> C = cumsum([true,~B]);
>> D = arrayfun(@(c)[A{c==C}],1:C(end),'UniformOutput',false);
We can check if this produces the correct result:
>> D
D =
[1x2 double] [1x7 double] [9] [1x6 double] [1x2 double] [1x3 double] [1x3 double]
>> D{2}
ans =
2.0000 3.0000 4.0000 4.0500 6.0000 7.0000 8.0000
This has correctly concatenated the matrices if their adjacent timestamps are less than 0.1 seconds apart.

Community Treasure Hunt

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

Start Hunting!