title: matlab histogram (with for loops)
body: <p>I'm doing an exercise where I have to plot the histogram of an image by reading each pixel's value. Then my idea is to loop through each color layers (r, g, b) and for each pixel store the value in a matrix. The following code runs but there it doesn't look right and I'm not totally sure why. First issue is that the graph is not a histogram with vertical bars and stacked values (How can I achieve that) and the second issue is that the graph is weird as it looks like the same values are applied for r, g and b, which is not possible given the images I'm using. Help? Thanks!</p>
  
  <pre><code>clc;
  clear;
  
  %% init values
  
  % loading initial image
  init_img = imread('face-1.jpg');
  
  % rgb matrixes
  r = zeros(256, 1);
  g = zeros(256, 1);
  b = zeros(256, 1);
  
  %% main loop
  
  % for each colour (r-g-b)
  for a = 1:size(init_img, 3)
  
      % loop through eache layer of the image
      for i = 1:size(init_img, 1)
          for j = 1:size(init_img, 2)
  
             if(a == 1)
                 for n = 1:size(r,1)
                  if(n == init_img(i, j, 1))
                      % get value (x) from n(th) row, column 1
                      x = r(n, 1);                    
                      r(n, 1) = x+1;
                  end
                 end
             elseif(a == 2)
                 for n = 1:size(g,1)
                  if(init_img(i, j, 1) == n-1)
                      % get value (x) from n(th) row, column 1
                      x = g(n, 1);                    
                      g(n, 1) = x+1;
                  end
                 end
             elseif (a == 3)
                 for n = 1:size(b,1)
                  if(init_img(i, j, 1) == n-1)
                      % get value (x) from n(th) row, column 1
                      x = b(n, 1);                    
                      b(n, 1) = x+1;
                  end
                 end
             end          
          end
      end
  end
  
  %% plot
  
  plot(r, 'Red');
  hold('on');
  plot(g, 'Green');
  hold('on');
  plot(b, 'Blue');
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/AUqCT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AUqCT.png" alt="histogram"></a></p>