How can I count the number of elements in a row satisfying a condition?
19 views (last 30 days)
Show older comments
Woonsup Choi
on 24 Nov 2015
Commented: Star Strider
on 24 Nov 2015
I have a vector looking like [0; 0; 0; -1.2; -0.4; 0; 0; 0; -3; -1.2; -2]. The non-zero numbers appear in two sequences. First, two of them in a row, and second, three of them. I would like to obtain an answer like [2;3], counting the number of elements in each sequence of non-zero values.
Thank you!
0 Comments
Accepted Answer
Star Strider
on 24 Nov 2015
One approach:
A = [0; 0; 0; -1.2; -0.4; 0; 0; 0; -3; -1.2; -2];
dA = [find(diff([A ~= 0])); length(A)]; % Detect Start, End Indices
dAr = reshape(dA, 2, []); % Reshape Into 2xN Matrix
Result = diff(dAr) % Subtract Columns
Result =
2 3
I don’t know how robust this is, but it works here.
2 Comments
Star Strider
on 24 Nov 2015
My pleasure.
If ‘dA’ has an odd number of elements, you may need to eliminate the last one, ‘length(A)’. It is easy to test for that:
if rem(length(dA),2) ~= 0
dA = dA(1:end-1);
end
before the reshape call.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!