MATLAB: Compare snr of quantized signals

quantizationsnr

Hi,
i should write some functions (calculate_snr and quantize) and then write a script that calculates the snr of quantized signals with 2-16 quantization bits. So i wrote them functions quantize (parameters: f: signal and n: quantization bits) and calculate_snr where I applied a random noise to the signal and return the snr between noisy signal and the orignal one.
Both functions here:
function [snr] = calculate_snr( f,n )
%CALCULATE_SNR Summary of this function goes here
% calc snr in db
% SNR = 10 log (S/N) from script
% generate noisy signal
%noise standard deviation
noisy = n*randn(size(f)); %noisy signal
snr = 10 * log(f/noisy);
end
The other one:
function f_q = myquantization( f, b)
max_steps= 2^b;
f_m = max(f)-min(f);
delta_q = f_m/(max_steps-1);
q = min(f):delta_q:max(f);
f_q = zeros(size(f));
for i=1:length(f)
[~,index_min] = min(abs(q-f(i)));
f_q(i) = q(index_min);
end
end
These functions work pretty well so far. But when I create an array and hold the results of calculations in this array and plot it over the quantization bits, I just dont see the result I was bein expecting. I expected that the signal is increasing as the SNR gets better with every bit (which I adjust in the quantization?). Instead, this is my result.
Here is how I generate it. I know I could probably do it a lot easier.
generate sine signal
[f,t] = sinusGenerator(1,3,0,0,1,0.001);
%Sine signal quantization
% quant bits 2-16
f_q2 = myquantization(f, 2);
f_q3 = myquantization(f, 3);
f_q4 = myquantization(f, 4);
f_q5 = myquantization(f, 5);
f_q6 = myquantization(f, 6);
f_q7 = myquantization(f, 7);
f_q8 = myquantization(f, 8);
f_q9 = myquantization(f, 9);
f_q10 = myquantization(f, 10);
f_q11 = myquantization(f, 11);
f_q12 = myquantization(f, 12);
f_q13 = myquantization(f, 13);
f_q14 = myquantization(f, 14);
f_q15 = myquantization(f, 15);
f_q16 = myquantization(f, 16);
% vector for snr results
f_snr = zeros(1,15);
f_snr(1) = calculate_snr(f_q2, 0.07);
f_snr(2) = calculate_snr(f_q3, 0.07);
f_snr(3) = calculate_snr(f_q4, 0.07);
f_snr(4) = calculate_snr(f_q5, 0.07);
f_snr(5) = calculate_snr(f_q6, 0.07);
f_snr(6) = calculate_snr(f_q7, 0.07);
f_snr(7) = calculate_snr(f_q8, 0.07);
f_snr(8) = calculate_snr(f_q9, 0.07);
f_snr(9) = calculate_snr(f_q10, 0.07);
f_snr(10) = calculate_snr(f_q11, 0.07);
f_snr(11) = calculate_snr(f_q12, 0.07);
f_snr(12) = calculate_snr(f_q13, 0.07);
f_snr(13) = calculate_snr(f_q14, 0.07);
f_snr(14) = calculate_snr(f_q15, 0.07);
f_snr(15) = calculate_snr(f_q16, 0.07);
x_axis = linspace(2,16,15);
plot(x_axis, f_snr)
Please excuse my English and I hope someone can help me out.

Best Answer

noisy is a 2D array, not a single number, so you'd need to use log(f ./ noisy). That's "dot slash" instead of simply slash.
Hopefully f is also a 2D array. If it's not, you'd need to change the noise generation to a 1-D vector instead of a 2-D array:
noisy = n * randn(1, size(f)); % 1-D noisy signal