codedude
codedude

Reputation: 6509

Quantize data in Matlab

Say I have some plot in Matlab like so:

x = linspace(0,10,10000);
input= sin(x);

I want to quantize the data to a certain number of bits. (I realize technically MATLAB quantizes all its graphs.) I've tried the following:

bits = 7;
output =floor(2^bits*input)/2^bits

But this only works if the input is between 0 and 1. What should I do?

Upvotes: 2

Views: 4074

Answers (1)

Divakar
Divakar

Reputation: 221514

Approach #1 bsxfun based "interpolating-looking" scheme -

x = linspace(min(input),max(input),2^bits) %// Setup the quantizied levels 
                                         %// ranging from min to max of the input data
[~,ind1] = min(abs(bsxfun(@minus,input,x.'))) %//' Find the indices of the 
                                              %// levels nearest to the input data
output = x(ind1) %// Get the quantized values

Also, try to not use variable names that are identical to built-in MATLAB function names, which is input in this case.


Approach #2 interp1 based -

x = linspace(min(input),max(input),2^bits) %// Setup the quantizied levels 
                                         %// ranging from min to max of the input data
output = interp1(x,x,input,'nearest') %// Get quantized values with 1-D interpolation
                                      %// to the nearest quantized levels

Example -

input [Input data] =
    0.8017    1.0533   -0.7489   -0.9363   -1.2691    0.4980    2.7891
bits [No. of bits used for quantization ] =
     2
x [These are 2^bits quantized levels ranging from min to max of input] =
   -1.2691    0.0836    1.4364    2.7891
output [Input data is brought to the nearest quantized levels taken from x] =
    1.4364    1.4364   -1.2691   -1.2691   -1.2691    0.0836    2.7891

Upvotes: 3

Related Questions