-1

This question is from chegg.com.

Given a vector a of N elements a_{n},n =1,2,...,N, the simple moving average of m sequential elements of this vector is defined as

mu(j) = mu(j-1) + (a(m+j-1)-a(j-1))/m   for j = 2,3,...,(N-m+1)

where

mu(1) = sum(a(k))/m    for k = 1,2,...,m

Write a script that computes these moving averages when a is given by a=5*(1+rand(N,1)), where rand generates uniformly distributed random numbers. Assume that N=100 and m=6. Plot the results using plot(j,mu(j)) for j=1,2,...,N-m+1.

My current code is below, but I'm not sure where to go from here or if it's even right.

close all 
clear all
clc 
N = 100; 
m = 6; 
a = 5*(1+rand(N,1)); 
mu = zeros(N-m+1,1); 
mu(1) = sum(a(1:m)); 
for j=2 
    mu(j) = mu(j-1) + (a-a)/m 
end 
plot(1:N-m+1,mu)
David
  • 8,449
  • 1
  • 22
  • 32
Stan-Lee
  • 11
  • 5
  • What is the question? Please don't just paste a link as it may go stale and then nobody will be able to understand what this is about. – John Paul Nov 14 '14 at 00:43
  • Given a vector a of N elements a_{n},n =1,2,...,N. The simple moving average of m sequential elements of this vector is defined as \mu _{j} = \mu _{j-1} + \frac{a_{m+j-1}-a_{j-1}}{m} j =2,3,...,(N-m+1) where \mu _{1} = \frac{1}{m}\sum_{k-1}^{m}a_{k} Write a script that computes these moving averages when a is given by a=5*(1+rand(N,1)), where rand generates uniformly distributed random numbers. Assume that N=100 and m=6. Plot the results using plot(j,\mu _{j}) for j=1,2,...,N-m+1. – Stan-Lee Nov 14 '14 at 00:47
  • Hope you can follow that.? – Stan-Lee Nov 14 '14 at 00:48

1 Answers1

0

I'll step you through the modifications.

Firstly, mu(1) was not fully defined. The equation given is slightly incorrect, but this is what it should be:

mu(1) = sum(a(1:m))/m;

then the for loop has to go from j=2 to j=N-m+1

for j=2:N-m+1

and at each step, mu(j) is given by this formula, the same as given in the question

mu(j) = mu(j-1) + (a(m+j-1)-a(j-1))/m

And that's all you need to change!

David
  • 8,449
  • 1
  • 22
  • 32