How to count continuous appearance of numeric values
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
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
Catégories
En savoir plus sur Introduction to Installation and Licensing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!