Search code examples
matlabvectorizationdate-histogram

Convert for loop into vector expression


I'm new to MATLAB and learning to use vector expressions instead of verbose for loops. I have a snippet and I was wondering whether it could even be written in a concise vector and if so how would I modify it.

for v = I
    X(i, v) = X(i, v) + length(I(I == v));
end

X is 1500x200

I is 3763x1

i can be thought of as a constant

What I'm doing here is this. I contains column indexes of X and I want to increment those locations by the number of times that particular index appeared in I. So after this for loop is done the ith row of X will contain a histogram.

Any other ideas or suggestions to improve my MATLAB coding would also be appreciated.


Solution

  • Here's a couple of ways:

    I = randi(10, [50,1]);  
    

    X = zeros (1, 10);
    for Col = 1 : size (X, 2)
      X(1, Col) = sum (I == Col);
    end
    % X = 7   7   3   3   7   4   5   8   1   5
    

    X = zeros (1, 10);
    for Col = I.'   % the transpose operation is needed to convert to horizontal!
      X(1, Col) += 1;
    end
    % X = 7   7   3   3   7   4   5   8   1   5
    

    X = zeros (1, 10);
    X = accumarray (I, ones (size (I)), size (X))
    % X = 7   7   3   3   7   4   5   8   1   5