Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: simple array relational problem
Date: Thu, 3 Mar 2011 07:15:22 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 41
Message-ID: <iknf6a$s2l$1@fred.mathworks.com>
References: <iknd4l$her$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: www-00-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1299136522 28757 172.30.248.45 (3 Mar 2011 07:15:22 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 3 Mar 2011 07:15:22 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:713566

"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 if-statements and array relational method, but the latter did not agree with the correct result (the if-statements 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