how to count the number of consecutive rows less than a given sum?
Show older comments
I have the following kind of data:
Data=[1; 2; 3; 8; 9; 10; 20; 30]
I want to count the number of consecutive rows which the difference between the first and the last element is less than or equal to 5.
For the example above, it would result in 3 counts:
-rows 1, 2 and 3 = 3
-rows 3 and 8 = 2
-rows 8, 9 and 10 = 3
In the end, I’d like to create a matrix in which the first column indicates the first row of the counting and the second column indicates the sum achieved:
Result =[1 3; 3 2; 8 3]
Many thanks in advance.
Flavio
5 Comments
Image Analyst
on 26 Oct 2015
For case 2, rows 3 and 8, the rows are not consecutive, which your subject line said is a requirement. Why do you have separated rows? Row 3 is not next to row 8.
For your last case you mention rows 8, 9, and 10. However your "Data" has only 8 rows! There is no row 9 or row 10!
This question needs a complete rewording.
Perhaps you can use rangefilt() in the Image Processing Toolbox.
Guillaume
on 26 Oct 2015
@IA, I think the user meant element of value 3 and 8 (which would be row 4 and 5).
@Flavio, your wording is indeed poor. When we say row 8, we mean the 8th row, which in your case is the element with value 30.
Image Analyst
on 26 Oct 2015
OK, for rows 6,7, & 8, the values are 10,20,& 30. So "the difference between the first and the last element" would be the difference from the element at row 6, which is 10, and the element at row 8, which is 30 to give a difference of 20. The requirement was that the difference "is less than or equal to 5." So how does Flavio say that there are 3 elements? I see zero elements because there are no elements within 5 of each other in those rows.
Flavio Silva
on 27 Oct 2015
The problem is that the variable out still exists from the last time that you ran my code. You should clear the variables from the MATLAB workspace and then run the code again.
Alternatively change the last two rows of code to this:
out = Data(R); % first element
out(:,2) = 1+C-R; % count elements
Accepted Answer
More Answers (0)
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!