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

采纳的回答

Star Strider
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
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
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.
  1 个评论
Mederic Mainson
Mederic Mainson 2016-5-17
Hi cyclist, Thanks for your answer, i could create function for sure, but i use to use histc and this would only take one line, so i think there probably is a way out there to repeat this behaviour...?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by