histcounts on matrice row by row, how to get rid of the loop?
12 ビュー (過去 30 日間)
古いコメントを表示
Hi All, I have got a simple Matrice let say M( double 10*100) I need histcounts of every row, so far i do:
MhistCountsRow=zeros(10,10)
for iLoop=1:10
MhistCountsRow(iLoop,:)=histcounts(M(iLoop,:));
end
I hate loop, i think they look disguting, how can i get rid of this one? Cheers Medie
0 件のコメント
採用された回答
Star Strider
2016 年 5 月 17 日
編集済み: Star Strider
2016 年 5 月 17 日
Interesting that histcounts will not do what hist does easily.
For an illustration, try this — no loops necessary:
x = randn(100,3);
[N,edges] = hist(x, 25, 1);
figure(1)
bar3(edges,N)
grid on
EDIT — Using a cell array with histcounts avoids the loop:
x = randn(3,100);
xc = mat2cell(x, ones(1,size(x,1)), size(x,2)); % Split Matrix Into Cells By Row
[hcell,hedges] = cellfun(@(x) histcounts(x,25), xc, 'Uni',0); % Do ‘histcounts’ On Each Column
hmtx = cell2mat(hcell); % Recover Numeric Matrix From Cell Array
edges = cell2mat(hedges); % Recover ‘edges’ For Each Histogram
7 件のコメント
Guillaume
2016 年 5 月 19 日
編集済み: Guillaume
2016 年 5 月 19 日
It's arguable that cellfun get rid of the loop. cellfun is just a loop by another name. The equivalent is commonly called foreach in other languages.
More importantly, you need to be aware that cellfun may actually be slower than a loop, particularly the way it is used here. You have the additional cost of computing a cell array, plus the cost of an anonymous function call on each element of the cell array, plus the cost of converting two cells arrays to matrices.
On the other hand cellfun and co. have the benefit of making it clear you operate on a whole sequence and that the same operation applies to each element of the sequence. See functional programming.
その他の回答 (1 件)
the cyclist
2016 年 5 月 17 日
According to the documentation,
"Data to distribute among bins, specified as a vector, matrix, or multidimensional array. If X is not a vector, then histcounts treats it as a single column vector, X(:)."
So, you are out of luck hoping to avoid a loop over several vectors.
Already, your bit of code is certainly much shorter than, say, the code for the histcounts function itself, which hides all the complexity of the histogram algorithm.
If you don't want to see the for loop, then I suggest you take a similar approach. Embed the for loop in a function of your own -- maybe call it histcountsMatrix, and then just call the function as a one-liner.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!