From: Mohau on
hi everyone
how can i use for loop function to calculate the individual mean from the following: matric size is [756 308], the increment between two values is 54. below is the mean done without using for loop function
Samp0 = mean (data(1:54,:));
Samp1 = mean (data(55:108,:));
Samp2 = mean (data(109:162,:));
Samp3 = mean (data(163:216,:));

thanks in advance for your help. . .
From: Oleg Komarov on
"Mohau " <phiri(a)sun.ac.za> wrote in message <hunedm$qpm$1(a)fred.mathworks.com>...
> hi everyone
> how can i use for loop function to calculate the individual mean from the following: matric size is [756 308], the increment between two values is 54. below is the mean done without using for loop function
> Samp0 = mean (data(1:54,:));
> Samp1 = mean (data(55:108,:));
> Samp2 = mean (data(109:162,:));
> Samp3 = mean (data(163:216,:));
>
> thanks in advance for your help. . .

Hi, I propose two approaches (vectorized and loop). The second is faster:
data = rand(756, 308);
tic
% Vectorized approach using accumarray
subs = reshape(repmat(1:ceil(756/54),54,1),[],1);
if size(subs,1) > 756
subs = subs(1:756);
end
subs = [repmat(subs,308,1), reshape(repmat(1:308,756,1),[],1)];
Out1 = accumarray(subs, data(:),[],@mean);
toc

tic
% Loop approach (almost 20 times faster)
finLoop = ceil(756/54);
Out2 = zeros(finLoop,308);
for jj = 1:finLoop
inWin = jj*54-53;
fiWin = jj*54;
Out2(jj,:) = mean(data(inWin:fiWin,:));
end
toc
isequalwithequalnans(Out1,Out2)

Oleg
From: Walter Roberson on
Mohau wrote:

> how can i use for loop function to calculate the individual mean from
> the following: matric size is [756 308], the increment between two
> values is 54. below is the mean done without using for loop function
> Samp0 = mean (data(1:54,:)); Samp1 = mean (data(55:108,:)); Samp2 = mean
> (data(109:162,:)); Samp3 = mean (data(163:216,:));
> thanks in advance for your help. . .

for K = 1 : 54 : size(data,1)
Samp{K} = mean(data(K:K+53,:));
end

I used {K} rather than (K) because mean of a matrix will operate along
columns, returning one value per column. If you want the mean of the entire block,

for K = 1 : 54 : size(data,1)
Samp(K) = mean(reshape(data(K:K+53,:),[],1));
end