How to generate pulses at 5khz with 0.01s duration and 0.09s delay?

只谈情不闲聊 提交于 2019-12-04 20:07:30
Trilarion

Now with pulstran.

A short documentation on pulstran. The syntax is:

y = pulstran(t, d, function_handle, p1, p2, ..)

and t are time steps for calculating the pulses (also the total time and dimensions of output), d are the pulse centers (shifting deltas) and p1, p2, .. are additional parameters to the function.

So the output is similar to the sum of function(t+d(i), p1, p2, ..) over all elements of d.

Here is the code:

function Untitled()

[t, y] = FreqGen(5e2, 20e3, 1, 1, 0.01, 0.1);
figure;
plot(t(1:3e3), y(1:3e3));
xlabel('time [s]');

end

function [t, y] = FreqGen(f, fs, T, A, Pulseduration, Interpulseduration)
% f - frequency of sine wave [Hz], fs - sampling frequency [Hz], T - total
% duration [s], A - amplitude of sine wave, Pulseduration [s],
% Interpulseduration [s]

% time steps
t = 0 : (1/fs) : T;

% pulse center steps
d = 0 : Interpulseduration : T;

% use pulstrans
y = pulstran(t, d, @my_pulse, A, f, Pulseduration);

end

function y = my_pulse(t, A, f, Tend)
% Sine pulse from 0 to Tend
    y = zeros(size(t));
    tx = t > 0 & t < Tend;
    y(tx) = A * sin(2 * pi * f * t(tx));
end

It's a bit slower though than the previous answer.

The documentation of pulstran is not really helpful. While one could look into the function directly it is actually the easiest way to implement what you want yourself (and you circumvent the Signal Processing Toolbox). Here I did it:

function Untitled()

[t, y] = FreqGen(5e2, 20e3, 1, 1, [0.01, 0.09]);
figure;
plot(t(1:3e3), y(1:3e3));
xlabel('time [s]');

end

function [t, y] = FreqGen(f, fs, T, A, Tr)
% f - frequency of sine wave [Hz], fs - sampling frequency [Hz], T - total
% duration [s], A - amplitude of sine wave, Tr - duration of high/low state
% of rectangular envelope pattern [s]

% time steps
t = 0 : (1/fs) : T;

% first the sine wave
ys = A * sin(2 * pi * f * t);

% then the rectangular envelope
yr = double(mod(t, sum(Tr)) < Tr(1));

% multiply both
y = ys .* yr;

end

The rectangular envelope is calculated with the help of modulo and a comparison.

And it looks like:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!