2013-10-10 55 views
0

嘿,我在这里得到一个奇怪的错误。这个函数只是找到一个数字的正确除数并返回它们。整数操作数错误

function [divisors] = SOEdivisors(num) 
%SOEDIVISORS This function finds the proper divisors of a number using the sieve 
%of eratosthenes 


    %check for primality 
    if isprime(num) == 1 
     divisors = [1]; 


    %if not prime find divisors 
    else 
     divisors = [0 2:num/2]; %hard code a zero at one. 

     for i = 2:num/2 
      if divisors(i) %if divisors i ~= 0 

       %if the remainder is not zero it is a divisor 
       if rem(num, divisors(i)) ~= 0 

        %remove that number and all its multiples from the list 
        divisors(i:i:num/2) = 0; 
       end 
      end 
     end 

     %add 1 back and remove all zeros 
     divisors(1) = 1; 
     divisors = divisors(divisors ~= 0); 
    end 
end 

我收到的错误是:

Integer operands are required for colon operator when used as index 

它指的是线23

线23

divisors(i:i:num/2) = 0; 

但我我和num都应该是整数。 ..我知道我是一个整数。但即使当我尝试

num = int8(num) 

或类似的东西,我仍然得到错误。

感谢您的阅读!

+0

实际上,如果你强制num是int类型的,你不应该得到这个错误(也许是一个不同的错误)。见'int8(5)/ 2'。 ----旁注:如果你不需要,不要强迫matlab使用数字转换为整数,它可能会让你感到意外,通常不会被要求。 –

回答

1

如果num是奇数则num/2不是整数...

0

你行只包含用于索引两个部分。

i 

num/2 

正如你已经提到inum是整数的唯一合乎逻辑的解释是,num是奇数。

然后num/2不会是整数。


也许你有兴趣使用fix(num/2)(这是将有效地为divisors的cretion使用),否则可能roundceil

0

当使用:

在命令的代码就意味着你知道结果是例如0.1或0.2或2.1的非点号。你应该有1或2或21。 您的结果也必须是无符号数字。例如:1或2或21不是-1或-2或-21。

然后使用带符号的int类型或从“fix();”命令中使用。 例如:

a=2.1; 

a=fix(a);那么“a”值将是2; 祝你有美好的一天。