# sum of two periodic signals with different length

So, I have those two signals (x1,x2) and I want to make a new signal (x) which is the sum of them. What bothers me here is the length of each one of the signals. I made this little code over here in matlab to plot x it for 2 common periods of it but I am not sure if this is right or not.

x1=[0 1 0.5 -0.5 -1 0];
x2=[0 0.8 0.8 0 -0.8 -0.8];
x=x1+x2;
t=2;
N=length(x);
n=0:t*N-1;
stem(n,[x x])


• Right for which purpose? What do you want to happen? Jan 31 '18 at 9:18
• just to make a new signal which is the sum of x1 and x2, nothing more than that. Jan 31 '18 at 9:55
• what is the sum of two signals of different lengths? Jan 31 '18 at 11:47
• the length of x1 is 5 whereas x2 is 6 and I am not sure if the answer I gave is right for calculating the sum of them because I added a 0 as the last element of x1 just to make the calculation. So I'm asking if this is right as a thought or it would give a false solution to the problem. Jan 31 '18 at 11:55
• It's not a mistake. MATLAB sums elements with same indexes. But this can become a problem for signals with much more elements. A better solution would be a function where you pass the elements for two signals and their length and the output should give you a vector with the elements of the new signal and the length of the new signal. Jan 31 '18 at 12:15

What you did is correct. All finite discrete signals have zeros to the left and to the right. Thus, if you want to sum two signals (arrays in MATLAB) you have to zero-pad the shortest one.

A generic solution for this could be written as follows (assuming you have two signals represented by row vectors, x1 and x2 and both start at the same instant of time, i.e. they are both zero until some index $n_0$):

l1 = length(x1);
l2 = length(x2);

if length(x1) < length(x2)
x1 = [x1 zeros(1,l2-l1)];
else
x2 = [x2 zeros(1,l1-l2)];
end


Note that if l1 == l2, the script does nothing, because it inserts a zero amount of zeros in x2.

Sidenote: as Marcus pointed out in the comments, if you want the periodicity to hold then adding a zero is not the solution. You should add as many samples as necessary to make both lengths match, just that not with zeros but with the values the periodic signal would take if it hadn't been truncated.

• I'd argue that on his case, the right thing to do would not have been padding with zero, but periodic continuation, since the zero breaks the periodicity! Jan 31 '18 at 17:02
• That's why I specified that this was valid for all finite signals. I'll add a sidenote though, as your observation is pertinent. Jan 31 '18 at 17:15