can this loop be vectorized ?

1 view (last 30 days)
Miguel Reina
Miguel Reina on 27 Nov 2017
Commented: Guillaume on 27 Nov 2017
I am trying to make a function for an histogram to explain the concept to students, is possible to vectorize this loop?
[x,y]=size(A);
freq=zeros(256,1);
for i=1:x
for j=1:y
value=A(i,j);
freq(value+1)=freq(value+1)+1;
end
end
thanks in advance.

Accepted Answer

Guillaume
Guillaume on 27 Nov 2017
Very simply with:
freq = accumarray(A(:), 1, [256, 1]);
  2 Comments
Miguel Reina
Miguel Reina on 27 Nov 2017
This error is appearing "Error using accumarray First input SUBS must contain positive integer subscripts." the Matrix A contains uint8 values and the size is 594x671
Guillaume
Guillaume on 27 Nov 2017
Yes, somehow I missed the +1 in your code. The correct answer should be:
freq = accumarray(A(:) + 1, 1, [256, 1]);

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!