How to count the total number of occurrences of each digit avoiding the first elements of each cell?

5 ビュー (過去 30 日間)
Suppose I have a cell array
C = {[1; 4; 7]; [2; 5; 8; 9]; [3; 4]};
c{:}
ans =
1
4
7
ans =
2
5
8
9
ans=
3
4
% where any digit won't repeat in the individual cell.
% There are 4 stages in this cell array.
% first stage elements are 1, 2, 3
% second stage elements are 4, 5, 4
% third stage elements are 7,8
% fourth stage elements are 9
I need to count the total number of occurrences of each digit except stage 1 that means by avoiding the first elements of each cell. Expected output:
Digit | Number of occurrences
4 2
5 1
7 1
8 1
9 1

採用された回答

Nick
Nick 2018 年 11 月 7 日
編集済み: Nick 2018 年 11 月 7 日
You could do the following if you don't mind using some for loops
% example data
C = {[1; 4; 7]; [2; 5; 8; 9]; [3; 4]};
% get the highest digit to make an array in which you store your count
highestDigit = max(cell2mat(C));
countArray = zeros(2, highestDigit);
% replace the second row with the digits
countArray(2,:) = 1:highestDigit;
% then loop over the cell array
for ii = 1:numel(C)
digits = C{ii}(2:end); % filter out the first digit
for jj=1:numel(digits)
countArray(1,digits(jj)) = countArray(1,digits(jj)) + 1; % add one every time it occurs
end
end
% remove the zeros
maskZeros = countArray(1,:)~=0;
countArray = countArray(:,maskZeros);
% print the result
fprintf('Digit | Number of occurrenced \n')
for ii = 1:length(countArray)
fprintf('%d %d \n',countArray(2, ii), countArray(1,ii));
end
  2 件のコメント
Md Shahidullah Kawsar
Md Shahidullah Kawsar 2018 年 11 月 7 日
Thanks. How can I plot the histogram of the number of occurrences?
Nick
Nick 2018 年 11 月 7 日
It depends how you want to display it:
Only showing the numbers that occurred you can do
figure;
binNames = strsplit(num2str(countArray(2,:)),' ');
h = histogram('Categories', binNames,'BinCounts', countArray(1,:));
Or if you want to show a real histogram by not removing the zeros. Just remove the following lines
maskZeros = countArray(1,:)~=0;
countArray = countArray(:,maskZeros);
and then add this command the end.
binEdges = [0, countArray(2,:)]+0.5;
h = histogram('BinEdges', binEdges,'BinCounts', countArray(1,:));
When first starting its always handy to explore the properties of the object handle (h) so you know how you can customize your histogram.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by