MATLAB / Octave : Increment array with an array of indexes

Viewed 379

I am struggling to optimize a piece of code. I will have to deal with many numbers (millions) and my code is running slow. Let's suppose that we have the matrix 3x3:

A = [ 8 1 6; 3 5 7; 4 9 2 ];

I want to know how many elements are in the intervals [0, 3), [3, 6) and [6, 9). Therefor, i need a matrix 1x3 :

p = [ 2 3 4 ];

My code is :

p = zeros(1, 3);
for i = 1 : 9
   p( floor(A / 3) + 1 ) += 1;

I want to do it without for loops, but the code :

p = zeros(1, 3);
p( floor(A / 3) + 1 ) += 1;

Outputs :

p = 1 1 1

Any ideas why? And how can i correct this issue?

2 Answers
Related