# How to program a summation of two variables in matlab

2

Basically I'm trying to program

for the function, which is then added random noise:

When M takes values of 5, 10 and 15.

What I have tried is:

``````clear all

n = 0:0.16:20;
k = 0;
X = cos((5*pi/4)*(n-k)) + sin(2*pi*(n-k) + pi/4);
Xr = X + (1.5*rand(1,length(X)) - 0.75); % x[n] con ruido aleatorio
Xrl = zeros(1,length(Xr),15);

figure(1)
plot(n,X,'b',n,Xr,'r--o')
grid on
title 'X[n] vs Xr[n]'
xlabel 'n'
ylabel 'Amplitud'

for M=[5 10 15]
for k = 0:M-1
Xrp = Xr;
Xrl(1,:,k+1) = Xrp;
end
Y = (1/M)*sum(Xrl,3); % Suma sobre la tercera dim. de Xrl por 1/M
figure(2)
plot(n,Y)
hold on
end
``````

The problem is that it returns the graph of figure 2 as a solid line, which would imply perfect adjustment for any M. Which is strange, my theory is that it is not evaluating for the variable k.

Thank you in advance for any help.

asked by cavereaper 06.03.2017 в 08:47
source

Your problem is assigning `Xrp` to `Xrl` . By assigning it directly without basically you are copying it repeatedly M times. After adding it and dividing it by M, you are receiving the same value.
What you have to do is to break `k` positions in each assignment of 'Xrp', so that the sum includes the M previous values of `Xrp` . You can do this with the `circshift`
`````` Xrl(1,:,k+1) = circshift(Xrp,[0,k]);