How can I count the number of elements in a row satisfying a condition?
16 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Star Strider
2015-11-24
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 个评论
Star Strider
2015-11-24
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!