Calculating the number of integers present after a specific value appears in an array

3 views (last 30 days)
I have an array with streams of 9s and 7s occasionally punctuated by single 0s, [0 7 7 7 7 9 0 9 9 9 9 7 0 7 7 7 7 0].
I want to write a loop that calculates the number of 7s and 9s after each 0, and then stops the calculation when it reaches the next 0. It would then go on to calculate the number of 7s and 9s after the next 0 and so on.
For example in [0 7 7 7 7 9 0 9 9 9 9 7], the output for the first 0 should be 4 sevens and 1 nine, while the output for the second 0 should be 4 nines and 1 seven.
I'm debating using a loop and if statement for this and using 'continue' when the next 0 is found in the array.
x = [0 7 7 7 7 9 0 9 9 9 9 7 0 7 7 7 7 0];
for i = 1:length(x)
if x (i) == 0 && x(i+1) ~= 0
y(i) = sum(x==7); %store number of times 7 appears for that 0
z(i) = sum(x==9);%store number of times 9 appears for that 0
elseif x(i+1) == 0 % if next 0 is found, continue to next iteration
continue
end
end
Issue: I'm not sure which function should be used to sum the number of times 7 and 9 after each 0. The function 'sum' just adds up all 7s and 9s in the array, not specific to those in between the 0s. Also, I don't know if a loop is truly essential for this?
Any help is really appreciated, thank you!

Accepted Answer

Guillaume
Guillaume on 29 May 2019
No need for a loop:
x = [0 7 7 7 7 9 0 9 9 9 9 7 0 7 7 7 7 0];
zerobin = cumsum(x(:) == 0);
run7s = accumarray(zerobin, x(:) == 7)
run9s = accumarray(zerobin, x(:) == 9)
  3 Comments
Guillaume
Guillaume on 29 May 2019
I forgot to say that you'll get an error if there's any 7 or 9 before the first 0, so make sure that it's never the case. Alternatively, add 1 to zerobin, in which case, the first element of run?s will be the count before the 1st zero.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!