# comm.ConvolutionalEncoder

Convolutionally encode binary data

## Description

The `comm.ConvolutionalEncoder` System object™ encodes a sequence of binary input vectors to produce a sequence of binary output vectors.

To convolutionally encode binary data:

1. Create the `comm.ConvolutionalEncoder` object and set its properties.

2. Call the object with arguments, as if it were a function.

## Creation

### Syntax

``convencoder = comm.ConvolutionalEncoder``
``convencoder = comm.ConvolutionalEncoder(trellis)``
``convencoder = comm.ConvolutionalEncoder(___,Name,Value)``

### Description

example

````convencoder = comm.ConvolutionalEncoder` creates a convolutional encoder System object.```

example

````convencoder = comm.ConvolutionalEncoder(trellis)` sets the `TrellisStructure` property to `trellis`.```

example

````convencoder = comm.ConvolutionalEncoder(___,Name,Value)` sets Properties using one or more name-value arguments in addition to any argument combinations in previous syntaxes. For example, `'TerminationMethod','Continuous'` specifies the termination method as continuous to retain the encoder states at the end of each input vector for use with the next input vector.```

## Properties

expand all

Unless otherwise indicated, properties are nontunable, which means you cannot change their values after calling the object. Objects lock when you call them, and the `release` function unlocks them.

If a property is tunable, you can change its value at any time.

Trellis description of the convolutional code, specified as a structure that contains the trellis description for a rate KN code. K is the number of input bit streams, and N is the number of output bit streams.

You can either use the `poly2trellis` function to create the trellis structure or create it manually. For more about this structure, see Trellis Description of a Convolutional Code and the `istrellis` function.

The trellis structure contains these fields.

Number of symbols input to the encoder, specified as an integer equal to 2K, where K is the number of input bit streams.

Data Types: `double`

Number of symbols output from the encoder, specified as an integer equal to 2N, where N is the number of output bit streams.

Data Types: `double`

Number of states in the encoder, specified as a power of 2.

Data Types: `double`

Next states for all combinations of current states and current inputs, specified as a matrix of integers. The matrix size must be `numStates`-by-2K.

Data Types: `double`

Outputs for all combinations of current states and current inputs, specified as a matrix of octal numbers. The matrix size must be `numStates`-by-2K.

Data Types: `double`

Data Types: `struct`

Termination method of the encoded frame, specified as one of these values.

• `'Continuous'` — The System object retains the encoder states at the end of each input vector for use with the next input vector.

• `'Truncated'` — The System object treats each input vector independently. The encoder states are reset at the start of each input vector. If you set the `InitialStateInputPort` property to `0` (`false`), the object resets its states to the all-zeros state. If you set the `InitialStateInputPort` property to `1`(`true`), the object resets its states to the values you specify in the `InitialStateInputPort` input.

• `'Terminated'` — The System object treats each input vector independently. For each input vector, the object uses extra bits to set the encoder states to all-zeros states at the end of the vector. For a rate K/N code, the object outputs a vector of length $N×\left(L+S\right)}{K}$, where S = constraintLength – 1 (or, in the case of multiple constraint lengths, S = sum(constraintLength(i)–1)). L is the length of the input. constraintLength – 1 is defined as log2(NumStates).

Data Types: `char` | `string`

Option to enable the encoder reset input, specified as a logical `1`(`true`) or `0` (`false`). Set this property to `1` (`true`) to enable the additional input to the object. When this additional reset input is a nonzero value, the internal states of the encoder reset to their initial conditions.

#### Dependencies

To enable this property, set the `TerminationMethod` property to `'Continuous'`.

Data Types: `logical`

Option to delay the output reset, specified as one of these logical values.

• `1` (`true`) — The reset of the internal states of the encoder occurs after the object computes the encoded data.

• `0` (`false`) — The reset of the internal states of the encoder occurs before the object computes the encoded data.

#### Dependencies

To enable this property, set the `ResetInputPort` property to `1` (`true`).

Data Types: `logical`

Option to enable the initial state input, specified as a logical `1` (`true`) or `0` (`false`). When you set this property to `1` (`true`), the object enables you to specify the initial state of the encoder for each input vector.

#### Dependencies

To enable this property, set the `TerminationMethod` property to `'Truncated'`.

Data Types: `logical`

Option to enable the final state output, specified as a logical `1` (`true`) or `0` (`false`). Set this property to `1` (`true`) to obtain the final state of the encoder as an output.

#### Dependencies

To enable this property, set the `TerminationMethod` property to `'Continuous'` or `'Truncated'`.

Data Types: `logical`

Source of the puncture pattern, specified as one of these values.

• `'None'` — The object does not apply puncturing.

• `'Property'` — The object punctures the code. This puncturing is based on the puncture pattern vector that you specify for the `PuncturePattern` property.

#### Dependencies

To enable this property, set the `TerminationMethod` property to `'Continuous'` or `'Truncated'`.

Data Types: `char` | `string`

Puncture pattern vector to puncture the encoded data, specified as a column vector. The vector must contain `1`s and `0`s, where `0` indicates the position of punctured bits or excluded bits.

#### Dependencies

To enable this property, set the `TerminationMethod` property to `'Continuous'` or `'Truncated'` and the `PuncturePatternSource` property to `'Property'`.

Data Types: `double`

## Usage

### Syntax

``codeword = convencoder(message)``
``codeword = convencoder(message,initstate)``
``codeword = convencoder(message,resetstate)``
``[codeword,finalstate] = convencoder(message)``

### Description

example

````codeword = convencoder(message)` encodes the input message using the convolutional encoding scheme specified by the trellis structure. `codeword` is the encoded codeword. `message` and `codeword` are column vectors of numeric, logical, or unsigned fixed-point values with word length 1 (fi (Fixed-Point Designer) object).```
````codeword = convencoder(message,initstate)` specifies the initial state of the encoder for each input vector. To enable this syntax, set the `TerminationMethod` property to `'Truncated'` and the `InitialStateInputPort` property to `1` (`true`).```
````codeword = convencoder(message,resetstate)` specifies the input to reset the internal states of the encoder. To enable this syntax, set the `TerminationMethod` property to `'Continuous'` and the `ResetInputPort` property to `1` (`true`).```
````[codeword,finalstate] = convencoder(message)` also returns the final state of the encoder. To enable this syntax, set the `FinalStateOutputPort` property to `1` (`true`) and the `TerminationMethod` property to `'Continuous'` or `'Truncated'`.```

### Input Arguments

expand all

Input message, specified as a binary-valued column vector.

Data Types: `double` | `int8` | `fi(data,0,1)`

Initial state of the encoder, specified as an integer.

#### Dependencies

To enable this argument, set the `TerminationMethod` property to `'Truncated'` and the `InitialStateInputPort` property to `1` (`true`).

Data Types: `double`

Reset for internal states of the encoder, specified as a numeric or logical `1` (`true`) or `0` (`false`).

#### Dependencies

To enable this argument, set the `TerminationMethod` property to `'Continuous'` and the `ResetInputPort` property to `1` (`true`).

Data Types: `double` | `logical`

### Output Arguments

expand all

Convolutionally encoded message, returned as a binary-valued column vector. This output vector has the same data type and orientation as input `message`.

When the convolutional encoder represents a rate K/N code, the length of the input vector equals K×L for some positive integer L. The object sets the length of this output vector, to L×N.

Data Types: `double` | `int8` | `fi(data,0,1)`

Final state of the encoder, returned as an integer.

#### Dependencies

To enable this argument, set the `TerminationMethod` property to `'Continuous'` or `'Truncated'`.

Data Types: `double`

## Object Functions

To use an object function, specify the System object as the first input argument. For example, to release system resources of a System object named `obj`, use this syntax:

`release(obj)`

expand all

 `step` Run System object algorithm `release` Release resources and allow changes to System object property values and input characteristics `reset` Reset internal states of System object

## Examples

collapse all

Transmit a convolutionally encoded 8 differential phase shift keying (DPSK) modulated bit stream through an additive white Gaussian noise (AWGN) channel. Then, demodulate and decode the modulated bit stream using a Viterbi decoder.

Create the necessary System objects.

```conEnc = comm.ConvolutionalEncoder; modDPSK = comm.DPSKModulator('BitInput',true); chan = comm.AWGNChannel('NoiseMethod','Signal to noise ratio (SNR)','SNR',10); demodDPSK = comm.DPSKDemodulator('BitOutput',true); vDec = comm.ViterbiDecoder('InputFormat','Hard'); error = comm.ErrorRate('ComputationDelay',3,'ReceiveDelay',34);```

Process the data by following these steps.

1. Generate random bits.

2. Convolutionally encode the data.

3. Apply DPSK modulation.

4. Pass the modulated signal through an AWGN channel.

5. Demodulate the noisy signal.

6. Decode the data using a Viterbi algorithm.

7. Collect error statistics.

```for counter = 1:20 data = randi([0 1],30,1); encodedData = conEnc(data); modSignal = modDPSK(encodedData); receivedSignal = chan(modSignal); demodSignal = demodDPSK(receivedSignal); receivedBits = vDec(demodSignal); errors = error(data,receivedBits); end```

Display the number of errors.

`errors(2)`
```ans = 3 ```

Encode and decode a sequence of bits using a convolutional encoder and a Viterbi decoder with a defined puncture pattern. Verify that the input and output bits are identical.

Define a puncture pattern matrix, and then reshape it into vector form for use with the encoder and decoder System objects.

```pPatternMat = [1 0 1;1 1 0]; pPatternVec = reshape(pPatternMat,6,1);```

Create a convolutional encoder and a Viterbi decoder in which the puncture pattern is defined by `pPatternVec`.

```conEnc = comm.ConvolutionalEncoder('PuncturePatternSource','Property','PuncturePattern',pPatternVec); viDec = comm.ViterbiDecoder('InputFormat','Hard','PuncturePatternSource','Property', ... 'PuncturePattern',pPatternVec);```

Create an error rate counter with the appropriate receive delay.

`error = comm.ErrorRate('ReceiveDelay',viDec.TracebackDepth);`

Encode a sequence of random bits, and then decode the encoded message.

```dataIn = randi([0 1],600,1); dataEncoded = conEnc(dataIn); dataOut = viDec(dataEncoded);```

Verify that no errors exist in the output data.

```errStats = error(dataIn,dataOut); errStats(2)```
```ans = 0 ```

Concatenated convolutional codes offer high reliability and have gained in prominence and usage as turbo codes. The `comm.TurboEncoder` and `comm.TurboDecoder` System objects support rate 1/n convolutional codes only. This example shows the parallel concatenation of two rate 2/3 convolutional codes to achieve an effective rate 1/3 turbo code by using `comm.ConvolutionalEncoder` and `comm.APPDecoder` System objects.

System Parameters

```blkLength = 1024; % Block length EbNo = 0:5; % Eb/No values to loop over numIter = 3; % Number of decoding iterations maxNumBlks = 1e2; % Maximum number of blocks per Eb/No value```

Convolutional Encoder/Decoder Parameters

```trellis = poly2trellis([5 4],[23 35 0; 0 5 13]); k = log2(trellis.numInputSymbols); % number of input bits n = log2(trellis.numOutputSymbols); % number of output bits intrIndices = randperm(blkLength/k)'; % Random interleaving decAlg = 'True App'; % Decoding algorithm modOrder = 2; % PSK-modulation order```

Initialize System Objects

Initialize Systems object™ for convolutional encoding, APP Decoding, BPSK modulation and demodulation, AGWN channel, and error rate computation. The demodulation output soft bits using a log-likelihood ratio method.

```cEnc1 = comm.ConvolutionalEncoder( ... 'TrellisStructure',trellis, ... 'TerminationMethod','Truncated'); cEnc2 = comm.ConvolutionalEncoder( ... 'TrellisStructure',trellis, ... 'TerminationMethod','Truncated'); cAPPDec1 = comm.APPDecoder( ... 'TrellisStructure',trellis, ... 'TerminationMethod','Truncated', ... 'Algorithm',decAlg); cAPPDec2 = comm.APPDecoder( ... 'TrellisStructure',trellis, ... 'TerminationMethod','Truncated', ... 'Algorithm',decAlg); bpskMod = comm.BPSKModulator; bpskDemod = comm.BPSKDemodulator( ... 'DecisionMethod','Log-likelihood ratio', ... 'VarianceSource','Input port'); awgnChan = comm.AWGNChannel( ... 'NoiseMethod','Variance', ... 'VarianceSource','Input port'); bitError = comm.ErrorRate; % BER measurement```

Frame Processing Loop

Loop through a range of ${\mathit{E}}_{\mathrm{b}}/{\mathit{N}}_{0}$ values to generate results for BER performance. The `helperTurboEnc` and `helperTurboDec` helper functions perform the turbo encoding and decoding.

```ber = zeros(length(EbNo),1); bitsPerSymbol = log2(modOrder); turboEncRate = k/(2*n); for ebNoIdx = 1:length(EbNo) % Calculate the noise variance from EbNo EsNo = EbNo(ebNoIdx) + 10*log10(bitsPerSymbol); SNRdB = EsNo + 10*log10(turboEncRate); % Account for code rate noiseVar = 10^(-SNRdB/10); for numBlks = 1:maxNumBlks % Generate binary data data = randi([0 1],blkLength,1); % Turbo encode the data [encodedData,outIndices] = helperTurboEnc( ... data,cEnc1,cEnc2, ... trellis,blkLength,intrIndices); % Modulate the encoded data modSignal = bpskMod(encodedData); % Pass the modulated signal through an AWGN channel receivedSignal = awgnChan(modSignal,noiseVar); % Demodulate the noisy signal using LLR to output soft bits demodSignal = bpskDemod(receivedSignal,noiseVar); % Turbo decode the demodulated data receivedBits = helperTurboDec( ... -demodSignal,cAPPDec1,cAPPDec2, ... trellis,blkLength,intrIndices,outIndices,numIter); % Calculate the error statistics errorStats = bitError(data,receivedBits); end ber(ebNoIdx) = errorStats(1); reset(bitError); end```

Display Results

While the practical wireless systems, such as LTE and CCSDS, specify base rate-1/n convolutional codes for turbo codes, the results show use of higher rate convolutional codes as turbo codes is viable.

```figure; semilogy(EbNo, ber, '*-'); grid on; xlabel('E_b/N_0 (dB)'); ylabel('BER'); title('High Rate Convolutional Codes for Turbo Coding'); legend(['N = ' num2str(blkLength) ', ' num2str(numIter) ' iterations']);```

Helper Functions

```function [yEnc,outIndices] = helperTurboEnc( ... data,hCEnc1,hCEnc2,trellis,blkLength,intrIndices) % Turbo encoding using two parallel convolutional encoders. % No tail bits handling and assumes no output stream puncturing. % Trellis parameters k = log2(trellis.numInputSymbols); n = log2(trellis.numOutputSymbols); cLen = blkLength*n/k; punctrVec = [0;0;0;0;0;0]; % assumes all streams are output N = length(find(punctrVec==0)); % Encode random data bits y1 = hCEnc1(data); y2 = hCEnc2( ... reshape(intrlv(reshape(data,k,[])',intrIndices)',[],1)); y1D = reshape(y1(1:cLen),n,[]); y2D = reshape(y2(1:cLen),n,[]); yDTemp = [y1D; y2D]; y = yDTemp(:); % Generate output indices vector using puncturing vector idx = 0 : 2*n : (blkLength - 1)*2*(n/k); punctrVecIdx = find(punctrVec==0); dIdx = repmat(idx, N, 1) + punctrVecIdx; outIndices = dIdx(:); yEnc = y(outIndices); end function yDec = helperTurboDec( ... yEnc,cAPPDec1,cAPPDec2,trellis, ... blkLength,intrIndices,inIndices,numIter) % Turbo decoding using two a-posteriori probability (APP) decoders % Trellis parameters k = log2(trellis.numInputSymbols); n = log2(trellis.numOutputSymbols); rCodLen = 2*(n/k)*blkLength; typeyEnc = class(yEnc); % Re-order encoded bits according to outIndices x = zeros(rCodLen,1); x(inIndices) = yEnc; % Generate output of first encoder yD = reshape(x(1:rCodLen),2*n,[]); lc1D = yD(1:n, :); Lc1_in = lc1D(:); % Generate output of second encoder lc2D = yD(n+1:2*n, :); Lc2_in = lc2D(:); % Initialize unencoded data input Lu1_in = zeros(blkLength,1,typeyEnc); % Turbo Decode out1 = zeros(blkLength/k,k,typeyEnc); for iterIdx = 1 : numIter [Lu1_out, ~] = cAPPDec1(Lu1_in,Lc1_in); tmp = Lu1_out(1:blkLength); Lu2_in = reshape(tmp,k,[])'; [Lu2_out, ~] = cAPPDec2( ... reshape(Lu2_in(intrIndices, :)',[],1),Lc2_in); out1(intrIndices, :) = reshape(Lu2_out(1:blkLength),k,[])'; Lu1_in = reshape(out1',[],1); end % Calculate llr and decoded bits for the final iteration llr = reshape(out1', [], 1) + Lu1_out(1:blkLength); yDec = cast((llr>=0), typeyEnc); end```

expand all

## References

[1] Clark, George C., and J. Bibb Cain. Error-Correction Coding for Digital Communications. Applications of Communications Theory. New York: Plenum Press, 1981.

[2] Gitlin, Richard D., Jeremiah F. Hayes, and Stephen B. Weinstein. Data Communications Principles. Applications of Communications Theory. New York: Plenum Press, 1992.

[3] Yasuda, Y., K. Kashiki, and Y. Hirata. “High-Rate Punctured Convolutional Codes for Soft Decision Viterbi Decoding.” IEEE Transactions on Communications 32, no. 3 (March 1984): 315–19. https://doi.org/10.1109/TCOM.1984.1096047.

[4] Haccoun, D., and G. Begin. “High-Rate Punctured Convolutional Codes for Viterbi and Sequential Decoding.” IEEE Transactions on Communications 37, no. 11 (November 1989): 1113–25. https://doi.org/10.1109/26.46505.

[5] Begin, G., D. Haccoun, and C. Paquin. “Further Results on High-Rate Punctured Convolutional Codes for Viterbi and Sequential Decoding.” IEEE Transactions on Communications 38, no. 11 (November 1990): 1922–28. https://doi.org/10.1109/26.61470.

[6] Moision, B. "A Truncation Depth Rule of Thumb for Convolutional Codes." In Information Theory and Applications Workshop (January 27 2008-February 1 2008, San Diego, California), 555-557. New York: IEEE, 2008.

## Version History

Introduced in R2012a