For loop for Sine wave function
조회 수: 22 (최근 30일)
이전 댓글 표시
I have a code for a swept sine wave function.
I was wondering, could the Line 22 'Variable appears to change size on every loop iteration..." be warded off somehow.
Also; if anyone knows how to perform FFT analysis on this script I would be most appretiate a little help.
I'm looking to produce a graph to show impluse response with respect to time and frequency response.
My code is:
T=5; %size of window
fs=44100; %sampling frequency
df=1/T; %frequency res
dt=1/fs; %time resolution
t=(0:+dt:T-dt); %time vector
df_t=500; %swept rate (Hz/seconds)
for i=1:+1:length(t)
%i=i+1;
if(i==1) %initialise f and t.
f=20; ti=0;
else
ti=ti+dt; %time increment
f=f+df_t*dt; %freq increment
end
w=2*pi*f; %omega
sweptsin(i)=sin(w*ti); %swept sine wave
end
plot(t, sweptsin)
xlim([0 0.1])
sound(sweptsin, fs)
Thanks
댓글 수: 0
채택된 답변
Voss
2022년 5월 23일
Yes, you can avoid that warning by pre-allocating sweptsin to the size it needs to be, which is the same size as t:
T=5; %size of window
fs=44100; %sampling frequency
df=1/T; %frequency res
dt=1/fs; %time resolution
t=(0:+dt:T-dt); %time vector
df_t=500; %swept rate (Hz/seconds)
% pre-allocate:
sweptsin = zeros(size(t));
for i=1:+1:length(t)
%i=i+1;
if(i==1) %initialise f and t.
f=20; ti=0;
else
ti=ti+dt; %time increment
f=f+df_t*dt; %freq increment
end
w=2*pi*f; %omega
sweptsin(i)=sin(w*ti); %swept sine wave
end
plot(t, sweptsin)
xlim([0 0.1])
However, you may want to consider doing the calculation without a for loop at all:
sweptsin = sin(2*pi*(20+df_t*dt*(0:numel(t)-1)).*t);
plot(t,sweptsin)
xlim([0 0.1])
댓글 수: 3
Voss
2022년 5월 23일
You're welcome!
Regarding the fft, maybe start a new question, and include the code you're running.
추가 답변 (1개)
Jan
2022년 5월 23일
편집: Jan
2022년 5월 23일
The warning is solved is solved by a pre-allocation. Insert before the loop:
T = 5; ´ % size of window
fs = 44100; % sampling frequency
% df = 1 / T; % frequency res [not used]
dt = 1 / fs; % time resolution
t = 0:dt:T-dt; % time vector
df_t = 500; % swept rate (Hz/seconds)
sweptsin = zeros(1, length(t)); % Pre-allocation
% A cleaner version of the loop:
f = 20;
for i = 1:numel(t)
w = 2 * pi * f; % omega
sweptsin(i) = sin(w * t(i)); % swept sine wave
f = f + df_t * dt; % freq increment
end
A more Matlabish way is to omit the loop:
f = zeros(size(t));
f(:) = df_t * dt; % All values
f(1) = 20; % Overwrite first element
f = cumsum(f); % Loop is hidden here
w = 2 * pi * f; % omega
sweptsin = sin(w .* t);
And even easier:
f = df_t * t + 20;
w = 2 * pi * f; % omega
sweptsin = sin(w .* t);
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!