MATLAB: Method to find the median/average of graph

audiodigital signal processinggraphMATLABSignal Processing Toolbox

I want to plot the median or average in graph. This is audio file in frequency domain and need to smoothen out the peak and converge them into two or three peaks as shown below. is there a specific code to do that?

Best Answer

Try this:
% Initialization steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 15;
% read file into memory */
[wave, fs]=audioread('1.wav');
% sound(wave, fs); % see what it sounds like */
t=0:1/fs:(length(wave)-1)/fs; % and get sampling frequency */
subplot(3, 1, 1)
%plot(t,wave)
plot(t, wave, 'b-');
title('Wave File', 'FontSize', fontSize);
ylabel('Amplitude', 'FontSize', fontSize);
xlabel('Length (in seconds)', 'FontSize', fontSize);
grid on;
L = length(wave);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(wave,NFFT)/L;
f = fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
subplot(3, 1, 2);
y = 2*abs(Y(1:NFFT/2+1));
plot(f, y, 'b-');
title('Single-Sided Amplitude Spectrum of y(t)', 'FontSize', fontSize);
xlabel('Frequency (Hz)', 'FontSize', fontSize);
ylabel('|Y(f)|', 'FontSize', fontSize);
grid on;
subplot(3, 1, 3);
y = 2*abs(Y(1:NFFT/2+1));
plot(f, y, 'b-');
title('Single-Sided Amplitude Spectrum of y(t)', 'FontSize', fontSize);
xlabel('Frequency (Hz)', 'FontSize', fontSize);
ylabel('|Y(f)|', 'FontSize', fontSize);
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
xlim([0, 400]);
% Smooth with a Savitzky Golay Filter
smoothy = sgolayfilt(y, 2, 101);
hold on;
plot(f, smoothy, 'r-', 'LineWidth', 2);
% Get the upper envelope
uppery = movmax(y,51);
% Smooth it out some
windowWidth = 31;
uppery = conv(uppery, ones(windowWidth, 1)/windowWidth, 'same');
plot(f, uppery, 'r-', 'LineWidth', 2);