MATLAB: Summation of 2 Sine waves

MATLABmatlab functionsine wave

Hi all,
I was hoping someone can help me wrap my head around why matlab does not add sine waves together.
Im trying to plot 2 added sine waves that are 180 degrees out of phase with the same amplitude. The added plot should show a stright line at 0 but im getting a strange array of signals.
If I plot the sine waves and sum wave on the some plot they seem to work which is confusing me even more.
here is my code.
A = 1 % Amplitude is 1 V
w = 2*pi*2; % w = 2Hz (frequency)
b = 2*pi/.5 % calculating wave length gives 0.5m
x = 0 :.005:1; % x axis from 0 to 1 with sampling every .005
L = 1; % length of transmission line
t = 0.0; % time = 0 (starting time)
%————————————————————————–
% signal generation
y = A*sin(b*x + (w*t)); % Wave equation for a transmission line
subplot(3,1,1);
plot (x, y);
axis ([0 1 -1.25 1.25]); % graph limits
grid on;
grid minor;
title ('Waveform Along A Transmission Line')
xlabel ('Metres');
ylabel ('Amplitude (V)');
set(gca, 'fontsize', 12); % change font size
%————————————————————————–
% Reflected wave
r = A*sin(b*(L-x)+ (w*t)); % reflected waveform, 180 out of phase
subplot(3,1,2);
plot (x, r);
axis ([0 1 -1.25 1.25]); % graph limits
grid on;
grid minor;
title ('Reflected Waveform Along A Transmission Line');
xlabel ('Metres');
ylabel ('Amplitude (V)');
set(gca, 'fontsize', 12); % change font size
%————————————————————————-
% Waveform sum
t = r + y;
subplot(3,1,3);
%plot (x,y);
%hold on;
%plot (x,r);
%hold on;
plot(x,t);
hold on;
I hope someone can clear up my mistake because it's driving me mad haha.
Jay

Best Answer

It does show a straight line at zero. Look at the magnitude of the y-axis (±2E-15), and you will see that it is essentially plotting floating-point approximation error.
Add:
ylim([-1 1])
to subplot(3,1,3) (so it’s the same as the others) and you get the result you expect.
The full code for it now being:
t = r + y;
subplot(3,1,3);
%plot (x,y);
%hold on;

%plot (x,r);
%hold on;
plot(x,t);
hold on;
ylim([-1 1])
.
Related Question