How to generate pulses at 5khz with 0.01s duration

2019-04-16 01:38发布

I want to generate a continous pulse in Matlab. I would like to generate the signal at 5khz with a duration of 0.01s, then nothing for 0.09s and then starting again. It's kind of a rectangular pulse, except it's in 5khz.

I have the following code to output a waveform for 0.01s at 5khz,

function [ output ] = FreqGen(  )
%UNTITLED3 Summary of this function goes here
%   Detailed explanation goes here
fs = 44100;
T = 0.01;
t = 0:(1/fs):T;
f = 5000;
a = 0.5;
output = a*sin(2*pi*f*t);
end

but I failed to figure out how to use Matlab function pulsetran to generate 0.09s pulses.

Just like the plot below:

enter image description here

2条回答
小情绪 Triste *
2楼-- · 2019-04-16 02:07

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:

enter image description here

查看更多
放我归山
3楼-- · 2019-04-16 02:21

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.

查看更多
登录 后发表回答