For loop for Sine wave function
23 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Voss
le 23 Mai 2022
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 commentaires
Voss
le 23 Mai 2022
You're welcome!
Regarding the fft, maybe start a new question, and include the code you're running.
Plus de réponses (1)
Jan
le 23 Mai 2022
Modifié(e) : Jan
le 23 Mai 2022
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);
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!