Method to find the median/average of graph
4 views (last 30 days)
Show older comments
Harindu Kodithuwakku
on 30 Apr 2018
Commented: Harindu Kodithuwakku
on 2 May 2018
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?
0 Comments
Accepted Answer
Image Analyst
on 2 May 2018
Edited: Image Analyst
on 2 May 2018
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);
More Answers (1)
Image Analyst
on 30 Apr 2018
Use the envelope() function, if you have the Signal Processing Toolbox. Or you can use sgolayfilt() or boundary(). Since it's so easy, you probably won't need help with that, but if you do, attach your data along with code to read it in.
See Also
Categories
Find more on Audio I/O and Waveform Generation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!