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

21 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Star Strider
Star Strider il 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 Commenti
Woonsup Choi
Woonsup Choi il 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 il 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.

Accedi per commentare.

Più risposte (0)

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by