MATLAB: Vectors, Sequential Elements and rand

90 Views Asked by At

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)
1

There are 1 best solutions below

0
On BEST ANSWER

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!