M.H
M.H

Reputation: 23

Create a sinusoidal wave with increasing steps frequencies matlab

I'm novice in matlab programing and I thank you in advance for your help. I would like to generate un sinus wave function starting to 0.25 Hz and increasing every 8 oscillations by 0.05 Hz until 0.7 Hz. The amplitude is constant.

I try this code:

cyc = 8; % number of cycles
for lF= 0.25:0.05:0.7 %% Frequency Increment
    t=1/fE:1/fE:(cyc/lF); % time per freq step
    wave = sin(2*pi*t)
end
plot(wave)

Thank you for your help.

Upvotes: 0

Views: 321

Answers (1)

Alexander Korovin
Alexander Korovin

Reputation: 1475

1) Try this:

cyc = 8; % number of cycles
wave = [];
T = [];
for f = 0.25:0.05:0.7 %% Frequency Increment
    t=0.01/f:0.01/f:(cyc/f); % time per freq step
    wave = [wave,sin(2*pi*f*t)];
    if isempty(T)
       T = t;
    else
       T = [T,T(end)+t];
    end
end
plot(T,wave)

2) Following to comment, the code with memory preallocation:

cyc = 8; % number of cycles
Npoints = 100; % number of points in one cycle
f = 0.25:0.05:0.7; %% Frequency Increment
Nf = length(f);

wave = zeros((cyc*Npoints-1)*Nf+1,1);
T    = zeros((cyc*Npoints-1)*Nf+1,1);
t0   = 0;
t_f  = linspace(0,cyc,cyc*Npoints); % time*frequency per freq step
for nf = 1:length(f)
    ind = (nf-1)*(cyc*Npoints-1)+(1:cyc*Npoints);
    wave(ind) = sin(2*pi*f(nf)*t_f);
    T(ind)    = t0 + t/f(nf);
    t0 = t0+cyc/f(nf);
end
plot(T,wave)

3) Vectorized version:

t    = cyc*linspace(0,1,cyc*Npoints)';
wave = sin(2*pi*t(:,ones(Nf,1)));
t = bsxfun(@plus,cumsum([0,cyc./f(1:end-1)]),bsxfun(@times,1./f,t))'; % for MATLAB version less than 2016b
[t,ind] = unique(t); wave = wave(ind); % remove duplicate values
plot(t,wave)

Upvotes: 1

Related Questions