Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to vectorize this loop
Date: Tue, 19 Apr 2011 02:04:05 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 29
Message-ID: <ioiqil\$42j\$1@fred.mathworks.com>
References: <ioinh4\$f1g\$1@fred.mathworks.com>
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 1303178645 4179 172.30.248.45 (19 Apr 2011 02:04:05 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 19 Apr 2011 02:04:05 +0000 (UTC)
Xref: news.mathworks.com comp.soft-sys.matlab:722623

"Mateusz Gos" <webmaster24@wp.pl> wrote in message <ioinh4\$f1g\$1@fred.mathworks.com>...
> hi,
> i would like to write the following loop in form of a vector, which I am guessing is possible (or not?):
>
> n = 1;
> for n = 1:20
> R = mean(measurements(1:n));
> n = n+1;
> end
>
> thanks,
> mat
- - - - - - - -
You should not have the "n = n+1;" line in there.  The for-loop with n takes care of advancing n.  Also the line "n = 1;" is totally unnecessary since the for-loop will start at n = 1 no matter how you set n in advance.

As your code stands at present you are taking twenty different mean operations, the first one the mean of the single number 1, then the mean of the two number 1 and 2, then that of 1, 2, and 3, and so forth.  Is that what you had in mind?  If so, all but the last one of these means from 1 to 20 have been overwritten because you placed them in the same variable R without indexing it with n.

If all you want is the single mean of the numbers from 1 to 20, then do this:

R = mean(1:20);

If you want the twenty different means, do this:

R = zeros(20,1);
for n = 1:20
R(n) = mean(1:n);
end

Roger Stafford