How to count frequency of non zero elements col wise

1 回表示 (過去 30 日間)
Vishal Sharma
Vishal Sharma 2017 年 6 月 30 日
コメント済み: Stephen23 2017 年 6 月 30 日
I have a matrix
A = [
1 2 3 0 0;
2 2 0 2 1;
1 0 2 3 1]
I want to count column wise frequency of occurrence of all non zero numbers, i.e. 1, 2, 3 So as to get result in form of
First Col 1 (2) 2(1) 3(0)
Second Col 1(0) 2(2) 3(0)
Third Col 1(0) 2(1) 3(1)
Forth Col 1(0) 2(1) 3(1)
Fifth Col 1(2) 2(0) 3(0)

採用された回答

Stephen23
Stephen23 2017 年 6 月 30 日
編集済み: Stephen23 2017 年 6 月 30 日
>> [N,C] = hist(A,0:3);
>> Z = N(C~=0,:).'
Z =
2 1 0
0 2 0
0 1 1
0 1 1
2 0 0
  2 件のコメント
Jan
Jan 2017 年 6 月 30 日
編集済み: Jan 2017 年 6 月 30 日
What a pitty that hist is "not recommended" anymore. Do you knwo a method to process the matrix directly using the modern histcounts or histogram? I miss hist and histc.
But it is still working and nicer than the loop: +1
Stephen23
Stephen23 2017 年 6 月 30 日
@Jan Simon: as I only have access to older MATLAB versions this topic has not yet come up for me... and why they needed to be replaced is not really very clear to me either.

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

その他の回答 (1 件)

Jan
Jan 2017 年 6 月 30 日
編集済み: Jan 2017 年 6 月 30 日
A = [1 2 3 0 0; ...
2 2 0 2 1; ...
1 0 2 3 1];
nCol = size(A, 2);
Edges = [unique(A(A ~= 0)); Inf];
Result = struct('N', cell(1, nCol));
for k = 1:nCol
Result(k).N = histcounts(A(:, k), Edges);
end
Or
Result = zeros(numel(Edges) - 1, nCol);
for k = 1:nCol
Result(:, k) = histcounts(A(:, k), Edges);
end

カテゴリ

Help Center および File ExchangeData Distribution Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by