Count number of true statements in a sequence until false, then check for the next true and repeat
古いコメントを表示
Greetings, the title might be a bit confusing, hope this example clarifies it.
The variable is a set of daily data where a climatological criterion is met (1) or not (0), and I want to count how many consecutive days the criterion is met, and do it for every time it is met after not being met.
I have a logical matrix of vectors (can be converted to single, double or any format) like this:
[0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1]
Which is divided into groups of zeroes and ones. That is, 6 zeroes followed by 3 ones, then 2 zeroes, 6 ones, 3 zeroes and 4 ones.
We see three groups of true values (1) separated by false values (0) with lengths of 3, 6, and 4 respectively.
Is there any way in Matlab for me to generate a vector that has the lenght of each individual true group (v=[3,6,4])?
採用された回答
その他の回答 (3 件)
V = [0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1] == 1;
V2 = [false V false] % Augment Vector
starts = strfind(V2, [0 1]) % Starting Indices
stops = strfind(V2, [1 0]) % Ending Indices (Offset)
lenv = stops - starts % Segment Lengths
These arguments are of course logical vectors, not strings or character arrays, however that does not matter to strfind.
starts = find(diff(V2) >= 1)
ends = find(diff(V2) <= -1)
lenv = stops - starts
This produces the same result.
NOTE -- The augmented vector ('V2' here) is necesary in order to create the [0 1] and [1 0] transitions at both ends of the original 'V' vector that this approach requires. If there are no transitions at the ends, the additional values are ignored.
.
Download this,
>> X=logical([0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1]);
>> [start,stop,v]=groupLims(groupTrue(X),1)
start =
7 12 21
stop =
9 17 24
v =
3 6 4
If this is time-critical, see: https://www.mathworks.com/matlabcentral/fileexchange/41813-runlength
x = logical([0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1]);
[b, n] = RunLength(x); % Or: RunLength_m(x), if you do not use a C compiler
result = n(b)
Or directly:
d = [true; diff(double(x)) ~= 0]; % TRUE if values change
b = x(d); % Elements without repetitions
k = find([d.', true]); % Indices of changes
n = diff(k); % Number of repetitions:
result = n(b)
カテゴリ
ヘルプ センター および File Exchange で MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!