How can I count the number of elements in a row satisfying a condition?
21 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Woonsup Choi
il 24 Nov 2015
Commentato: Star Strider
il 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 Commenti
Risposta accettata
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
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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!