I would like to quantize a Sinewave correctly, and identify where the issues is with my code
23 views (last 30 days)
Show older comments
Hi,
With the code below, I am trying to Quantize the Sinewave by varying the quantity of bits from 16-bits down via Bit Shifting, and then play a sound.
The waveform is normalised, however I am not replicating the waveform correctly and I just cannot seem to find where my error is.
I have attached some .jpg files at nBits = 1, 8 and 15.
Any help or guidance would be very appreciated.
% Sampling Frequency
fs = 8000;
% Sample Period
Ps = 1/fs;
% Sample Time from zero to two seconds in 125us steps (Ps)
t = 0:Ps:2;
% Waveform Frequency
waveFreq = 2;
% Sinewave signal
waveSignal = sin(2*pi*waveFreq*t);
waveInt = int16(waveSignal*2^15);
% Quantize waveform via truncation. (Reduce the least significant bit - LSB)
nBits = 1;
quantWave = bitshift(waveInt,nBits);
% Cast waveform back into a double data type
quantWaveDub = double(quantWave)/2^(16-nBits);
% Normalise the waveform due to bit change
quantWaveDub = quantWaveDub/max(abs(quantWaveDub));
% Plot Sinewave signal
figure(1);
plot(t,waveSignal);
ylim([-1.5 1.5]);
sound(waveSignal,fs);
pause(1);
% Plot Quantized signal
figure(2);
plot(t,quantWaveDub);
ylim([-1.5 1.5]);
sound(quantWaveDub,fs);
0 Comments
Accepted Answer
Les Beckham
on 21 Jun 2024
Edited: Les Beckham
on 21 Jun 2024
You were so close! But bitshift shifts left by the specified number of bits. Use a minus sign to shift right.
% Sampling Frequency
fs = 8000;
% Sample Period
Ps = 1/fs;
% Sample Time from zero to two seconds in 125us steps (Ps)
t = 0:Ps:2;
% Waveform Frequency
waveFreq = 2;
% Sinewave signal
waveSignal = sin(2*pi*waveFreq*t);
waveInt = int16(waveSignal*2^15);
% Quantize waveform via truncation. (Reduce the least significant bit - LSB)
nBits = 1;
quantWave = bitshift(waveInt, -nBits); % <<<<< minus sign to shift right!
% Cast waveform back into a double data type
quantWaveDub = double(quantWave)/2^(16-nBits);
% Normalise the waveform due to bit change
quantWaveDub = quantWaveDub/max(abs(quantWaveDub));
% Plot Sinewave signal
figure(1);
plot(t,waveSignal);grid on
ylim([-1.5 1.5]);
% sound(waveSignal,fs);
% pause(1);
% Plot Quantized signal
figure(2);
plot(t,quantWaveDub); grid on
ylim([-1.5 1.5]);
% sound(quantWaveDub,fs);
2 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!