Element-wise subtraction of two stem plots to form an array

3 views (last 30 days)
I am having trouble subtracting one stem plot from another of the same size. Whenever I run my code due to the subtraction of x[n]-xhat[n] I recieve a different array every time, and therefore calculations like error signal and mean squared error MSE change every time I run the program. Is this because Matlab does not recognize that the stem plots are discrete? Here is my code:
a = [1 -1/4];
b = [1];
Number_of_samples = 200;
Time_length = 20;
Ts = Time_length / (Number_of_samples - 1);
n = 0 : Ts : Time_length;
%real signal, non-periodic
x = ((0.9) .^ n) .* cos(2 * pi .* n);
subplot(4, 2, 1);
stem(n, x, 'filled');
title('Input Signal x[n]');
xlabel('n');
ylabel('x[n]');
d= sqrt(0.04)*randn(size(y))+1;%Gaussian noise
subplot(4,2,3)
stem(n,d,'filled');
title('Gaussian Noise d[n]');
xlabel('n');
ylabel('d[n]');
e=[1];
f=[1 -1/4];
xhat=filter(e,f,yhat_new);
subplot(4,2,6);
stem(n,xhat,'filled');
title('Output Signal xhat[n]');
xlabel('n');
ylabel('xhat[n]');
error = x-xhat; %Error between two signals
sqrd_err = error.^2; %Taking element-wise sum of the error vector
MSE = mean(sqrd_err,'all');
energy_signal = sum(error.^2); %Energy Signal
Again, I am having trouble with element-wise subtraction of two stem plots. I am able to get a correct stem plot of the subtraction, but I need specific values like error signal and MSE.

Accepted Answer

Cris LaPierre
Cris LaPierre on 15 Mar 2021
Edited: Cris LaPierre on 15 Mar 2021
Subtraction is always elementwise.
Your numbers change each time because you are using random numbers
d= sqrt(0.04)*randn(size(y))+1; % Gaussian noise
^^^^^
This signal ultimately ends up in xhat, hence the constantly changing result.
  2 Comments
Samantha Bartos
Samantha Bartos on 15 Mar 2021
Good catch, thanks! I need to add Gaussian noise to my signal, so is there a way around the random function?
Cris LaPierre
Cris LaPierre on 15 Mar 2021
That will depend on what you need to do. Gaussian noise is random.

Sign in to comment.

More Answers (0)

Categories

Find more on Audio I/O and Waveform Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!