Effacer les filtres
Effacer les filtres

there is always zero elements

1 vue (au cours des 30 derniers jours)
MD
MD le 10 Juin 2019
Commenté : Star Strider le 10 Juin 2019
Hi. right now i am tryign to learn descriptive statistics and produce them in matlab environment.
let us consider,
c = [ 1 2 3 4 5 6 7 8]
for i=1:2:length(c)
m(i)=(c(i)+c(i+1))/2;
end
disp(m)
But there is always zero elements in m. Why is this happening? how can i get m without any zero element?
Please if there is anyone to help.
Thanks in advance.

Réponse acceptée

Star Strider
Star Strider le 10 Juin 2019
The reason is that your ‘i’ index skips the even-numbered elements, so the even-numbered elements are set to 0.
The easiest way to avoid that is to just use a separate counter:
c = [ 1 2 3 4 5 6 7 8]
k = 1;
for i=1:2:length(c)
m(k)=(c(i)+c(i+1))/2;
k = k + 1;
end
disp(m)
  1 commentaire
Star Strider
Star Strider le 10 Juin 2019
Actually, since you want to take the mean of adjacent pairs of elements, rather than adjacent elements, using the reshape function on your vector, and then taking the mean of the resulting matrix is likely most efficient:
m = mean(reshape(c(:), 2, []))
The result is the same.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by