MATLAB: Need to find numbers divisible by 2 through 100

find values divisible by

hi i want to count the values in given vector/matrix that are divisible by 2-100.
y has few thousand random digits.
here is the code that i stitched but its giving me error. i want to create a vector divby which holds count of all values divisible by specific number and increment its corresponding value in value in the index .. say count of values divisible by 7 are held in divby(y) .. and after each iteration if a value is divisble by 7 divby[7] should increment by 1.
y=[3 3 43 45 2 2 34 5 ] % (it has a lot of such random values (most are 6 figure values)
divby=[];
ndivby=[];
for k=2:99
for i=1:length(y)
if(mod(y(i),k)==0)
divby(k)=divby(k)+1;
else
ndivby(k)=ndivby(k)+1;
end
end
end
i am getting below error Index exceeds matrix dimensions.
Error in all25k3rd (line 60) divby(k)=divby(k)+1;
Please help

Best Answer

Preallocate your arrays like this instead of as empty arrays:
divby=zeros(1,99);
ndivby=zeros(1,99);
Related Question