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

 Akzeptierte Antwort

the cyclist
the cyclist am 21 Mai 2016

0 Stimmen

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

Weitere Antworten (3)

Azzi Abdelmalek
Azzi Abdelmalek am 21 Mai 2016

0 Stimmen

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 Kommentar

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

Melden Sie sich an, um zu kommentieren.

Chamjiee Tramadol
Chamjiee Tramadol am 21 Mai 2016

0 Stimmen

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 am 21 Mai 2016

0 Stimmen

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

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by