"John Wong" wrote in message <iknd4l$her$1@fred.mathworks.com>...
> Given an array n is all integers from 1 to 30, and array y is given by two conditions.
> If n is divisible by 3,5,or 7, y is square root of n, otherwise, y is zero.
>
> I tested with ifstatements and array relational method, but the latter did not agree with the correct result (the ifstatements is right in this case).
>
> n = 1:30;
> y= (n.^(1/2)).*(mod(n,3)==0) + (n.^(1/2)).*(mod(n,5)==0) + (n.^(1/2)).*(mod(n,7)==0) + 0;
> sum(y) % gives 79.3984
>
> for n = 1:30
> if(mod(n,3) == 0)
> y(n) = n^(1/2);
> else if (mod(n,5)==0)
> y(n) = n^(1/2);
> else if(mod(n,7)==0)
> y(n) = n^(1/2);
> else
> y(n)= 0;
> end
> end
> end
> end
> sum(y) % gives 65.4656
>
> I got the right answer by writing this little demo code
> % z = [ 3 5 6 7 9 10 12 14 15 18 20 21 24 25 27 28 30]
> % for n = 1:17
> % g(n) = z(n).^(1/2);
> % end
> % sum(g)
>
> My question is, where is my mistake??? Can anyone spot one?
>
> Thank you!
        
In your first method the integers 15, 21, and 30 each get counted twice because they are each multiples of two of the divisors 3, 5, and 7, not just one. That accounts for the difference in your results:
79.3984  65.4656 = sqrt(15) + sqrt(21) + sqrt(30)
Roger Stafford
