Filter löschen
Filter löschen

there is always zero elements

1 Ansicht (letzte 30 Tage)
MD
MD am 10 Jun. 2019
Kommentiert: Star Strider am 10 Jun. 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.

Akzeptierte Antwort

Star Strider
Star Strider am 10 Jun. 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 Kommentar
Star Strider
Star Strider am 10 Jun. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by