what can I do to prevent overwriting in for loop?

I have a data file recording a parameter every 1sec. I wrote a for loop to average each 60 rows to get 1 reading every 1min. what happened is that the code overwrite the results in the variable. help neede to correct the following code: for i=1:length(x) z=mean(x(i:i+59,:)) i=i+60 end variable z contain only one row. what can I do to prevent overwriting in for loop?

Réponses (2)

Iain
Iain le 29 Août 2014
z(i) = mean(x(i:i+59,:));

4 commentaires

zeinab
zeinab le 29 Août 2014
Modifié(e) : zeinab le 29 Août 2014
for i=1:length(x)
z(i)=mean(x(i:i+59,:))
i=i+60;
end
??? In an assignment A(I) = B, the number of elements in B and I must be the same.
@zeinab,
Your code defined different values for i. First, you said i = 1,2,3, to whatever length of x is. But in the loop, you defined i=i+60 (I'm assuming this is for the purpose of averaging the 60 rows), but at the next loop, MATLAB would use i=2.
r = 1:60:length(x)
for i=1:
z(i)=mean(x(r(i):r(i)+59,:))
end
Iain
Iain le 29 Août 2014
z(i,:) = mean(x(i:i+59,:));
zeinab
zeinab le 29 Août 2014
Modifié(e) : zeinab le 29 Août 2014
@HIKARU, thanks for reply, and i will try this way. @lain, the loop doesn't stop :)

Connectez-vous pour commenter.

for cnt=1:fix(length(x)/60)
z(cnt)=mean(x((cnt-1)*60+1:cnt*60));
end
But it's faster to not do it with a loop:
z=mean(reshape(x(1:fix(length(x)/60)*60),60,[]));
You shouldn't use i as variable as it's also the imaginary unit. And don't change the value of the increment in the loop, this won't have the desired effect.

2 commentaires

zeinab
zeinab le 29 Août 2014
thnks for reply but what are cnt,reshape,and fix?
cnt is a variable, "counter". Better name than i. reshape is a function which changes the shape of an array without changing the number of elements. E.g. change a 4x1 into a 2x2 array. fix is cutting everything after the decimal separator. In case the length of x is not exactly a multiple of 60, the program would crash if this fix thing isn't taken.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Question posée :

le 29 Août 2014

Commenté :

le 29 Août 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by