how to count the number of consecutive rows less than a given sum?
2 views (last 30 days)
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
Stephen23
on 27 Oct 2015
Edited: Stephen23
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
Stephen23
on 26 Oct 2015
Edited: Stephen23
on 27 Oct 2015
Data = [1; 2; 3; 8; 9; 10; 20; 30];
X = bsxfun(@minus,Data(:).',Data(:));
Y = fliplr(0<X & X<=5);
Z = fliplr(Y & cumsum(Y,1)==1 & cumsum(Y,2)==1);
[R,C] = find(Z);
out = Data(R); % first element
out(:,2) = 1+C-R; % count elements
The code produces this output:
>> out
out =
1 3
3 2
8 3
EIDT to make out allocation replace existing out.
2 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!