I'm trying to multiply sin waves / cosine waves recursively but I'm not sure why my answers are so different. Y2 in blue is what I'm trying to get but the FOR loop which is Y in red is what is produced any idea how to fix the FOR loop Y? see plot and code below ?
Fs = 8000;% Sampling frequency
t=linspace(0,1,Fs);
y=zeros(1,length(t));
y = .5*sin(2*pi*2*t);
for ii=1:1:3
y=y.*y;
end
plot(y,'r')
hold on
y2=(.5*sin(2*pi*2*t)).* (.5*sin(2*pi*2*t)).*(.5*sin(2*pi*2*t)); %should look like this
plot(y2,'b') %both plots should look like this
PS: I'm using octave 3.8.1 which is like matlab
You're multiplying eight times here
y = .5*sin(2*pi*2*t);
for ii=1:1:3
y=y.*y;
ii=1:1:3 is inclusive, so you do y=y.*y three times.
First time it becomes y = y^2,
Second time it become y^4 = y^2*y*2
Third time it becomes y^8 = y^4*y^4
This would be a solution:
Fs = 8000;% Sampling frequency
t=linspace(0,1,Fs);
y=zeros(1,length(t));
y = .5*sin(2*pi*2*t);
result = ones(1,length(t));
for ii=1:1:3
result=result.*y;
end
plot(result,’r’)
hold on
y2=(.5*sin(2*pi*2*t)).* (.5*sin(2*pi*2*t)).*(.5*sin(2*pi*2*t)); %should look like this
plot(y2,'b') %both plots should look like this
In all iteration, y.*y make square of updated y.
Fs = 8000;% Sampling frequency
t=linspace(0,1,Fs);
y=ones(1,length(t));
x = .5*sin(2*pi*2*t);
for ii=1:1:3
y=y.*x;
end
plot(y,'r')
hold on
y2=(.5*sin(2*pi*2*t)).* (.5*sin(2*pi*2*t)).*(.5*sin(2*pi*2*t)); %should look like this
plot(y2,'b') %both plots should look like this
Maybe, you want this code.
Related
This is a question for a hand in in one of my courses, just want to state that.
What I am trying to do is sampling a square wave, take the fourier transform (fft) and plot the answer to graph. This is how I have achieved this:
Fs = 100;
Ts = 1/Fs;
N = 8192;
Tmax = (N - 1)*Ts;
t = 0:Ts:Tmax;
x = square(t);
X = fft(x,N);
plot(t, abs(X))
What it return is a graph that looks like this
This looks almost as inspected, but since I do not know what to expect with the square wave I also try to do it with a $\sin(2*t)$ wave. If I take the fourier transform on this, I should get 2 spiks, each at 2 and -2 (right side). But what I get is something like this
(Note! I have zoomed in on the left hand side of the graph to show that the spike is not at 2) As you can see the spike is not where it is supposed to be. I can than conclude that probably the 1 graph is not eater how it should be.
Is it something wrong with my x axis representation? And if so, how do I convert the x axis into the frequency plane?
The frequencies resulting from the FFT range from 0 to the sampling frequency. Specifically, the horizontal axis of the FFT corresponds to frequencies 0, fs/N, 2*fs/N, ... ,(N-1)*fs/N, where fs is the sample frequency and N is the FFT size.
So, you should modify the horizontal axis in the plot to the following, where N is numel(t) and fs is computed as 1/(t(2)-t(1)):
freq_axis = (0:numel(t)-1)/numel(t)/(t(2)-t(1));
plot(freq_axis, abs(X))
You may also want to apply fftshift to observe frequencies from -fs/2 to fs/2, instead of from 0 to fs. In that case:
freq_axis = (-numel(t)/2:numel(t)/2-1)/numel(t)/(t(2)-t(1));
plot(freq_axis, fftshift(abs(X)))
As a check, with your example x = sin(2*t) the second plot gives:
Comparing your sin(2*t) with the generic expression sin(2*pi*f*t), the frequency f of that sinusoid is seen to be 1/pi = 0.3183, in agreement with the figure.
t = 0:.001:.2;
f=10;
x=sin(2*pi*f*t);
n=15;
y=sin(2*pi*n*t);
x(x<=0) = 0;
plot(t,x);
hold on
plot(t,y);
this is the waveform that i need
togenerate:
and this is the waveform i have so far:
the first part its a simple sin but the second part when the sin doesn't go
into the negative part I am struggling with when I set it the negative
interval to 0 its going to be 0 for the whole interval not just for a point
The supplied image has two sine waves plotted next to each other, of which the one has a negative sign.
How about this:
t = -4:0.1:4;
y = 0.5.*sign(t).*sin(t*4)
plot(t,y)
I have adapted the code in Comparing FFT of Function to Analytical FT Solution in Matlab for this question. I am trying to do FFTs and comparing the result with analytical expressions in the Wikipedia tables.
My code is:
a = 1.223;
fs = 1e5; %sampling frequency
dt = 1/fs;
t = 0:dt:30-dt; %time vector
L = length(t); % no. sample points
t = t - 0.5*max(t); %center around t=0
y = ; % original function in time
Y = dt*fftshift(abs(fft(y))); %numerical soln
freq = (-L/2:L/2-1)*fs/L; %freq vector
w = 2*pi*freq; % angular freq
F = ; %analytical solution
figure; subplot(1,2,1); hold on
plot(w,real(Y),'.')
plot(w,real(F),'-')
xlabel('Frequency, w')
title('real')
legend('numerical','analytic')
xlim([-5,5])
subplot(1,2,2); hold on;
plot(w,imag(Y),'.')
plot(w,imag(F),'-')
xlabel('Frequency, w')
title('imag')
legend('numerical','analytic')
xlim([-5,5])
If I study the Gaussian function and let
y = exp(-a*t.^2); % original function in time
F = exp(-w.^2/(4*a))*sqrt(pi/a); %analytical solution
in the above code, looks like there is good agreement when the real and imaginary parts of the function are plotted:
But if I study a decaying exponential multiplied with a Heaviside function:
H = #(x)1*(x>0); % Heaviside function
y = exp(-a*t).*H(t);
F = 1./(a+1j*w); %analytical solution
then
Why is there a discrepancy? I suspect it's related to the line Y = but I'm not sure why or how.
Edit: I changed the ifftshift to fftshift in Y = dt*fftshift(abs(fft(y)));. Then I also removed the abs. The second graph now looks like:
What is the mathematical reason behind the 'mirrored' graph and how can I remove it?
The plots at the bottom of the question are not mirrored. If you plot those using lines instead of dots you'll see the numeric results have very high frequencies. The absolute component matches, but the phase doesn't. When this happens, it's almost certainly a case of a shift in the time domain.
And indeed, you define the time domain function with the origin in the middle. The FFT expects the origin to be at the first (leftmost) sample. This is what ifftshift is for:
Y = dt*fftshift(fft(ifftshift(y)));
ifftshift moves the origin to the first sample, in preparation for the fft call, and fftshift moves the origin of the result to the middle, for display.
Edit
Your t does not have a 0:
>> t(L/2+(-1:2))
ans =
-1.5000e-05 -5.0000e-06 5.0000e-06 1.5000e-05
The sample at t(floor(L/2)+1) needs to be 0. That is the sample that ifftshift moves to the leftmost sample. (I use floor there in case L is odd in size, not the case here.)
To generate a correct t do as follows:
fs = 1e5; % sampling frequency
L = 30 * fs;
t = -floor(L/2):floor((L-1)/2);
t = t / fs;
I first generate an integer t axis of the right length, with 0 at the correct location (t(floor(L/2)+1)==0). Then I convert that to seconds by dividing by the sampling frequency.
With this t, the Y as I suggest above, and the rest of your code as-is, I see this for the Gaussian example:
>> max(abs(F-Y))
ans = 4.5254e-16
For the other function I see larger differences, in the order of 6e-6. This is due to the inability to sample the Heaviside function. You need t=0 in your sampled function, but H doesn't have a value at 0. I noticed that the real component has an offset of similar magnitude, which is caused by the sample at t=0.
Typically, the sampled Heaviside function is set to 0.5 for t=0. If I do that, the offset is removed completely, and max difference for the real component is reduced by 3 orders of magnitude (largest errors happen for values very close to 0, where I see a zig-zag pattern). For the imaginary component, the max error is reduced to 3e-6, still quite large, and is maximal at high frequencies. I attribute these errors to the difference between the ideal and sampled Heaviside functions.
You should probably limit yourself to band-limited functions (or nearly-band-limited ones such as the Gaussian). You might want to try to replace the Heaviside function with an error function (integral of Gaussian) with a small sigma (sigma = 0.8 * fs is the smallest sigma I would consider for proper sampling). Its Fourier transform is known.
I have a series of 2D measurements (time on x-axis) that plot to a non-smooth (but pretty good) sawtooth wave. In an ideal world the data points would form a perfect sawtooth wave (with partial amplitude data points at either end). Is there a way of calculating the (average) period of the wave, using OCTAVE/MATLAB? I tried using the formula for a sawtooth from Wikipedia (Sawtooth_wave):
P = mean(time.*pi./acot(tan(y./4))), -pi < y < +pi
also tried:
P = mean(abs(time.*pi./acot(tan(y./4))))
but it didn't work, or at least it gave me an answer I know is out.
An example of the plotted data:
I've also tried the following method - should work - but it's NOT giving me what I know is close to the right answer. Probably something simple and wrong with my code. What?
slopes = diff(y)./diff(x); % form vector of slopes for each two adjacent points
for n = 1:length(diff(y)) % delete slope of any two points that form the 'cliff'
if abs(diff(y(n,1))) > pi
slopes(n,:) = [];
end
end
P = median((2*pi)./slopes); % Amplitude is 2*pi
Old post, but thought I'd offer my two-cent's worth. I think there are two reasonable ways to do this:
Perform a Fourier transform and calculate the fundamental
Do a curve-fitting of the phase, period, amplitude, and offset to an ideal square-wave.
Given curve-fitting will likely be difficult because of discontinuities in saw-wave, so I'd recommend Fourier transform. Self-contained example below:
f_s = 10; # Sampling freq. in Hz
record_length = 1000; # length of recording in sec.
% Create noisy saw-tooth wave, with known period and phase
saw_period = 50;
saw_phase = 10;
t = (1/f_s):(1/f_s):record_length;
saw_function = #(t) mod((t-saw_phase)*(2*pi/saw_period), 2*pi) - pi;
noise_lvl = 2.0;
saw_wave = saw_function(t) + noise_lvl*randn(size(t));
num_tsteps = length(t);
% Plot time-series data
figure();
plot(t, saw_wave, '*r', t, saw_function(t));
xlabel('Time [s]');
ylabel('Measurement');
legend('measurements', 'ideal');
% Perform fast-Fourier transform (and plot it)
dft = fft(saw_wave);
freq = 0:(f_s/length(saw_wave)):(f_s/2);
dft = dft(1:(length(saw_wave)/2+1));
figure();
plot(freq, abs(dft));
xlabel('Freqency [Hz]');
ylabel('FFT of Measurement');
% Estimate fundamental frequency:
[~, idx] = max(abs(dft));
peak_f = abs(freq(idx));
peak_period = 1/peak_f;
disp(strcat('Estimated period [s]: ', num2str(peak_period)))
Which outputs a couple of graphs, and also the estimated period of the saw-tooth wave. You can play around with the amount of noise and see that it correctly gets a period of 50 seconds till very high levels of noise.
Estimated period [s]: 50
I am trying to compare the FFT of exp(-t^2) to the function's analytical fourier transform, exp(-(w^2)/4)/sqrt(2), over the frequency range -3 to 3.
I have written the following matlab code and have iterated on it MANY times now with no success.
fs = 100; %sampling frequency
dt = 1/fs;
t = 0:dt:10-dt; %time vector
L = length(t); %number of sample points
%N = 2^nextpow2(L); %necessary?
y = exp(-(t.^2));
Y=dt*ifftshift(abs(fft(y)));
freq = (-L/2:L/2-1)*fs/L; %freq vector
F = (exp(-(freq.^2)/4))/sqrt(2); %analytical solution
%Y_valid_pts = Y(W>=-3 & W<=3); %compare for freq = -3 to 3
%npts = length(Y_valid_pts);
% w = linspace(-3,3,npts);
% Fe = (exp(-(w.^2)/4))/sqrt(2);
error = norm(Y - F) %L2 Norm for error
hold on;
plot(freq,Y,'r');
plot(freq,F,'b');
xlabel('Frequency, w');
legend('numerical','analytic');
hold off;
You can see that right now, I am simply trying to get the two plots to look similar. Eventually, I would like to find a way to do two things:
1) find the minimum sampling rate,
2) find the minimum number of samples,
to reach an error (defined as the L2 norm of the difference between the two solutions) of 10^-4.
I feel that this is pretty simple, but I can't seem to even get the two graphs visually agree.
If someone could let me know where I'm going wrong and how I can tackle the two points above (minimum sampling frequency and minimum number of samples) I would be very appreciative.
Thanks
A first thing to note is that the Fourier transform pair for the function exp(-t^2) over the +/- infinity range, as can be derived from tables of Fourier transforms is actually:
Finally, as you are generating the function exp(-t^2), you are limiting the range of t to positive values (instead of taking the whole +/- infinity range).
For the relationship to hold, you would thus have to generate exp(-t^2) with something such as:
t = 0:dt:10-dt; %time vector
t = t - 0.5*max(t); %center around t=0
y = exp(-(t.^2));
Then, the variable w represents angular frequency in radians which is related to the normalized frequency freq through:
w = 2*pi*freq;
Thus,
F = (exp(-((2*pi*freq).^2)/4))*sqrt(pi); %analytical solution