MATLAB: Finding index values for consecutive values in cell array

4dcell arrayhelp

Hi all,
I have a 4d cell array: 105 x 3 x3 x 2000 . I would like to find the average number of consecutive values above a threshold value in the 2000 frames throughout 105cells
105 cells look abit like this: (made up numbers)
val(:,:,1) =
1 2 1
6 3 2
1 2 2
to -> val(:,:,2000) =
1 2 1
1 3 2
1 2 1
I would like to find the maximum value in each 2000 cells of my 105 cells ( so 6 for val(:,:,1) and 3 for val(:,:,2000) in this case for cell 1 ). I want set a threshold of a number say 6 ( so only finds val(:,:,1) in this case). Then I want to know how many frames it was above this threshold value for.. so maybe val(:,:,1) to val(:,:,7) which would be 7 frames.
An average of the number of these frames throughout the whole cell array would be ideal.
I am not so good at coding so I need all the help I can get. Thank you in advance!

Best Answer

Right, so your data is a 105x1 vector cell array of 3x3x2000 matrices.
First, a function to get the average length of the sequences in a vector:
function meanlength = averagesequencelength(sequence)
%sequence: a logical vector of any shape. The code does not check that the input is indeed a vector
transitions = find(diff([false; sequence(:); false])); %find location transitions between false;true and true;false. Padding to ensure that the sequence always start with a false;true transition and ends on a true;false transition
seqlengths = transitions(2:2:end) - transitions(1:2:end); %we're guaranteed that the number of transitions is even due to the padding
meanlength = mean(seqlengths);
if isnan(meanlength) %will happen if there is no sequence at all
meanlength = 0;
end
end
Then to apply to your cell array:
threshold = 19;
result = cellfun(@(m) averagesequencelength(max(m, [], [1 2]) >= threshold), SNRcellarray)
Note that the above use the new dimension syntax for max introduced in R2018b. In earlier versions:
result = cellfun(@(m) averagesequencelength(max(max(m, [], 1), [], 2) >= threshold), SNRcellarray)