How to count continuous appearance of numeric values
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2016-11-20
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 个评论
更多回答(1 个)
Guillaume
2016-11-20
编辑:Guillaume
2016-11-20
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Web Services 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!