How to count continuous appearance of numeric values
1 view (last 30 days)
Show older comments
Hi,
I have below matrix, and I want count (a) what is the maximum count that numerical appeared continuously, (2) total count of numerical (by column wise).
2 N/A
4 8
3 7
N/A 1
N/A N/A
5 9
4 2
3 2
1 5
N/A 8
N/A N/A
My desired output is (do not consider N/A):
maxCount:
4 5 (column1 maximum numerical continuous appearance is 4, column2 maximum continuous numerical appearance is: 5)
totalCount:
7 8
0 Comments
Accepted Answer
Walter Roberson
on 20 Nov 2016
ncol = size(YourArray, 2);
mask = [true(1, ncol); isnan(YourArray); true(1, ncol)] .';
maxcount = zeros(1, ncol);
totalcount = zeros(1, ncol);
for col = 1 : ncol
starts = strfind( mask(col, :), [1 0]);
ends = strfind( mask(col, :), [0 1]);
maxcount(col) = max(ends-starts);
end
totalcount(:) = sum(~mask, 2);
0 Comments
More Answers (1)
Guillaume
on 20 Nov 2016
Edited: Guillaume
on 20 Nov 2016
I'm assuming the N/A are actually NaN, otherwise your question does not make sense as your input is not valid syntax in matlab.
m = [2 NaN; 4 8; 3 7; NaN 1; NaN; NaN; 5 9; 4 2; 3 2; 1 5; NaN 8; NaN NaN];
totalCount is easy:
totalCount = sum(~isnan(m));
For maxCount it's a little bit more complicated but you can obtain the information from a combination of isnan, find and diff. Unfortunately, find does not work by column so you have to loop over the whole matrix:
maxCount = cellfun(@(nancolumn) max(diff([0; find(nancolumn); size(m, 1)+1]) - 1), num2cell(isnan(m), 1))
The cellfun above is equivalent to:
maxCount = zeros(1, size(m, 2));
nanm = isnan(m);
for column = 1 : size(m, 2)
nancolumn = nanm(:, column);
nanidx = find(nancolumn);
runlengths = diff([0; nanidx; size(m, 1)+1] - 1;
maxCount(1, column) = max(runlengths);
end
0 Comments
See Also
Categories
Find more on Web Services in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!