Given the time sequence t and period T, I would like to generate a rectangular pulse train with random magnitude in Matlab like in the figure below:
I used the square function and generate the figure like below, but the magnitude is not the same in a period. I want the magnitude remains the same in a period.
Is there an efficient and elegant way in Matlab?
You can generate a set of random pulse heights, then for each point turn it into a pulse (where the signal is non-zero) and a "gap" (where the signal is 0).
Here is some example code, see the comments for details
numPulses = 20; % number of pulses to generate
pulseWidth = 10; % width (in samples) of each pulse
gapWidth = 15; % width (in samples) of each gap between pulses
pulseMin = 3; % minimum pulse height
pulseMax = 10; % maximum pulse height
% generate array of random pulse heights
pulseHeights = rand(1,numPulses) * (pulseMax-pulseMin) + pulseMin;
% Make all of the final samples, defined as either a pulse or a gap
pulses = repmat( pulseHeights, pulseWidth, 1 );
gaps = zeros( gapWidth, numPulses );
% Turn the matrix of pulses/gaps into a single array
signal = reshape( [pulses; gaps], [], 1 );
% Plot. Using the 'stairs' function gives straight edges, but could use 'plot'
figure;
stairs( signal );
ylim( [-1, pulseMax+1] );