# How do i do this in MATLAB?

3 views (last 30 days)
Nathan Jaqua on 29 Sep 2019
Answered: Walter Roberson on 29 Sep 2019
I've got 2 noise vectors(x1 and x2) that I need to add to the pwelch command but I can't figure out what's wrong with my code. How do I add the 2 vectors together for the pwelch command? please help. code is below
f1 = 4000; %sinusoidal frequency
A1 = 0.2; %amplitude
f2 = 5000; %sinusoidal frequency
A2 = 0.25; %amplitude
t1 = 0:1/f1:5-1/f1;
t2 = 0:1/f2:5-1/f2;
x1 = A1*cos(2*pi*f1*t)+randn(size(t1));
x2 = A2*cos(2*pi*f2*t)+randn(size(t2));
x = x1+x2;
[pxx,f] = pwelch(x,500,300,500,Fs);
plot(f,10*log10(pxx)); xlabel('Frequency (Hz)'); ylabel('PSD (dB/Hz)');

Walter Roberson on 29 Sep 2019
>> size(t1)
ans =
1 20000
>> size(t2)
ans =
1 25000
Your x1 is the same size as t1, and your x2 is the same size as t2. x1+x2 is therefore attempting to add a vector of length 20000 and a vector of length 25000.
You are using the wrong approach.
f1 = 4000; %sinusoidal frequency
A1 = 0.2; %amplitude
f2 = 5000; %sinusoidal frequency
A2 = 0.25; %amplitude
secs = 5;
N = lcm(f1*secs, f2*secs); %lowest common multiple
t = linspace(0, secs, N+1);
t(end) = [];
x1 = A1*cos(2*pi*f1*t)+randn(size(t));
x2 = A2*cos(2*pi*f2*t)+randn(size(t));
You should consider whether the randn should be at full magnitude or should be multiplied by A1 or A2 . As it is you have 5 times as much noise as you have signal for x1.
You do not really need the full lcm() samples over 5 seconds, but using the lcm() ensures that there are an exact integer number of cycles for each of f1 and f2 in those 5 seconds.
I am, though, seeing some clipping in cos(2*pi*f1*t) that I cannot quite explain at the moment.