Matlab - problem with snr function

9 vues (au cours des 30 derniers jours)
jnc
jnc le 12 Nov 2021
Commenté : dpb le 12 Nov 2021
I have to add noise to recorded audio, so as SNR of result signal should be equal 3dB.
The idea is to calculate SNR of recorded audio and generated gaussian noise. According to that ratio I want to scale noise and then add it to recorded audio
I convert file to vector using audioread function:
[ y, fsampl] = audioread('123.wav');
And then I generate gaussian noise:
noise = normrnd(0,1,1,length(y));
Next I want to calculate signal to noise ratio using snr() function:
cur_snr= snr(y, noise);
But i get an error:
Error using snr
Expected input number 2, Fs, to be a scalar.
Error in snr>timeSNR (line 187)
validateattributes(fs,{'numeric'},{'real','finite','scalar','positive'}, ...
Error in snr (line 157)
[r, noisePow] = timeSNR(plotType, harmType, Args{:});
Error in untitled4 (line 10)
cur_snr= snr(y, noise);
I have no idea what can be wrong. What i checked:
-audio file is read corectly
-noise and y vector has the same length

Réponse acceptée

dpb
dpb le 12 Nov 2021
The two inputs have to have the same orientation as well as same length.
You've created a row vector above for the noise while undoubtedly the input signal y is a column vector.
I just checked here and that is the error message you get in that case -- it's not very informative relative to the cause of the error: TMW could have done better in either dealing with the inputs as it finds them inside the function or at least providing a meaningful error message.
Use
noise = normrnd(0,1,size(y));
instead to make the two commensurate in size automagically.
  2 commentaires
jnc
jnc le 12 Nov 2021
That's it. Thank you
dpb
dpb le 12 Nov 2021
I've got another bug report to submit after the precision issue with datetime and duration and nsec resolution; I'll add an enhancement request on snr as well -- at least fix the error message if not handle vectors of different orientations silently.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 12 Nov 2021
This works fine:
[y, fs] = audioread('guitartune.wav');
subplot(3, 1, 1);
plot(y, 'b-');
grid on;
title('Perfect Signal', 'FontSize', 20)
noiseAmplitude = 0.05 * max(y)
noise = noiseAmplitude * normrnd(0,1,1, length(y));
% Make a column vector like y
noise = noise(:);
subplot(3, 1, 2);
plot(noise, 'b-');
grid on;
title('Noise Alone', 'FontSize', 20)
% Create noisy signal
noise_y = y + noise;
subplot(3, 1, 3);
plot(noise_y, 'b-');
grid on;
cur_snr= snr(y, noise)
caption = sprintf('Noisy Signal. SNR = %.2f', cur_snr);
title(caption, 'FontSize', 20)

Tags

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by