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

荒凉一梦 提交于 2019-12-06 12:33:26

问题


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:


回答1:


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.




回答2:


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:



来源:https://stackoverflow.com/questions/28420084/how-to-generate-pulses-at-5khz-with-0-01s-duration-and-0-09s-delay

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