Series of consecutive numbers (different lengths)

I would appreciate it if someone showed me an easy way to do this. Let them say that I have a vector in MATLAB, for example

d = [3 2 4 2 2 2 3 5 1 1 2 1 2 2 2 2 2 9 2] 

I want to find a series of consecutive "twos" numbers and the lengths of these rows.

The twos number can be easily found on x=find(d==2) . But I want to get a vector containing the lengths of all series of consecutive twos numbers, which means that my result in this case will be the same:

 [1 3 1 5 1]. 

Who could help me?

+6
source share
3 answers

It works:

 q = diff([0 d 0] == 2); v = find(q == -1) - find(q == 1); 

gives

 v = 1 3 1 5 1 

for me

+9
source

This is called the path length . For him there is a good m file http://www.mathworks.com/matlabcentral/fileexchange/4955-rle-deencoding . This method is generally faster than the previously placed diff / find path.

 tic d_rle = rle(d==2); d_rle{2}(d_rle{1}==1); toc 

Elapsed time is 0.002632 seconds.

 tic q = [0 diff([0 d 0] == 2)]; find(q == -1) - find(q == 1); toc 

The elapsed time is 0.003061 seconds.

+6
source

What if we need the indices of the original matrix, where the sequential values โ€‹โ€‹are located? Further, what if we want to get a matrix of the same size as the original matrix, where the number of consecutive values โ€‹โ€‹is stored in the consecutive value indices? For instance:

  original_matrix = [1 1 1;2 2 3; 1 2 3]; output_matrix = [3 3 3;2 2 0;0 0 0]; 

This issue is related to the quality control of meteorological data. For example, if I have a temperature data matrix from several sensors, and I want to know which days had constant consecutive values โ€‹โ€‹and how many days were constant, so I can then mark the data as possible malfunctions.

matrix temperature is the number of days x the number of stations, and I want the output matrix to also be the number of days x the number of stations where consecutive values โ€‹โ€‹are marked as described above.

-1
source

Source: https://habr.com/ru/post/899791/


All Articles