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

조회 수: 21 (최근 30일)
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);

채택된 답변

Les Beckham
Les Beckham 2024년 6월 21일
편집: Les Beckham 2024년 6월 21일
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);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by