0

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.

Rabeez Riaz
  • 442
  • 5
  • 15
  • 2
    there's a function which can be used to do exactly what you're after. Look at `accumarray`. (also, your code seems to have logical errors; why would you iterate over I and then repeat the number of times an element repeats in I each time you encounter it again?) – Tasos Papastylianou Jul 19 '17 at 23:30
  • Yeah, I just noticed that bug too, fixing it now. I'll look at the function you mentioned and get back to you. – Rabeez Riaz Jul 19 '17 at 23:36

1 Answers1

1

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
Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57