need to find numbers divisible by 2 through 100

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

 Respuesta aceptada

the cyclist
the cyclist el 21 de Mayo de 2016
Preallocate your arrays like this instead of as empty arrays:
divby=zeros(1,99);
ndivby=zeros(1,99);

Más respuestas (3)

Azzi Abdelmalek
Azzi Abdelmalek el 21 de Mayo de 2016
There is a problem with your initialization, it should be zero instead of empty variable.
divby=[];
ndivby=[];
And also look at this part of your code
if(mod(y(i),k)==0)
divby(k)=divby(k)+1;
else
ndivby(k)=ndivby(k)+1;
end

1 comentario

i hope it is achieving what i want . to see if there is a value other then 0 then either decrement or increment.
new to matlab dont will find a way t get c style increments to work. also code is not optimized thats for sure but ok

Iniciar sesión para comentar.

Chamjiee Tramadol
Chamjiee Tramadol el 21 de Mayo de 2016
modified code as below
divby=zeros(1,99);
ndivby=zeros(1,99);
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
while the error has gone. but i am not getting desired results..
var divby contains a lot of strange values. Columns 97 through 99
279 321 279
Chamjiee Tramadol
Chamjiee Tramadol el 21 de Mayo de 2016

0 votos

thanks Azizi and cyclist both for your prompt responses. it resolved my issue.

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Preguntada:

el 21 de Mayo de 2016

Respondida:

el 21 de Mayo de 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by