Effacer les filtres
Effacer les filtres

I would like to quantize a Sinewave correctly, and identify where the issues is with my code

11 vues (au cours des 30 derniers jours)
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);

Réponse acceptée

Les Beckham
Les Beckham le 21 Juin 2024
Modifié(e) : Les Beckham le 21 Juin 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 commentaires
Dan Lardner
Dan Lardner le 22 Juin 2024
Hi Les,
Of course, thanks for pointing that out.
It was drivig me crazy.

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by