How can I count the number of elements in a row satisfying a condition?

19 views (last 30 days)
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!

Accepted Answer

Star Strider
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
Woonsup Choi
Woonsup Choi on 24 Nov 2015
Thank you for the quick answer. When dA has an odd number of elements, reshape did not work. I'll think about it.
Star Strider
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!