histcounts on matrice row by row, how to get rid of the loop?
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Mederic Mainson
il 17 Mag 2016
Modificato: Guillaume
il 19 Mag 2016
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 Commenti
Risposta accettata
Star Strider
il 17 Mag 2016
Modificato: Star Strider
il 17 Mag 2016
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 Commenti
Guillaume
il 19 Mag 2016
Modificato: Guillaume
il 19 Mag 2016
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.
Più risposte (1)
the cyclist
il 17 Mag 2016
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.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!