MATLAB: Area under curve that is plotted from a txt file

area_under_curveMATLABplot from txt file

This question is building on the solution given here. I have attached a simulated noise plot and wanted to get the same effect of shading the area under the graph between x = 300 to x = 3000. How can I go about getting the plot to show the shaded region under the curve between x = 300 to x = 3000 although the simulated points data file do not contain x = 300 and x = 3000.
% Select file
clear;
clc;
[FileName,PathName] = uigetfile('*.txt','Select data file');
fid = fopen( strcat(PathName,FileName) ,'rt' );
% Read the file and store into matrix v
i = 0;
v = [0 0];
while feof(fid) == 0
buffer = fscanf(fid, '%f', 2);
buffer = buffer';
if i == 0;
v = buffer;
else
v = vertcat(v,buffer);
end
i = i + 1;
end
% Frequency vector
freq = v(:,1);
% Phase noise vector
pnoise = v(:,2);
subplot(1, 2, 1);
semilogx(freq,pnoise); grid on; axis([100 10^5 -160 -70]);
title('Original Plot');
xlabel('Frequency (Hz)'); ylabel('Amplitude');
subplot(1, 2, 2);
semilogx(freq,pnoise)
grid on; axis([0 10^5 -160 -70]);
hold on
title('Plot with Area Shaded');
xlabel('Frequency (Hz)'); ylabel('Amplitude');
idx=freq>300&freq<3000;
minpnoise = pnoise(find(idx,1,'last'));
patch([300 freq(idx) 3000 300], [-160 pnoise(idx) -160 -160], [1 0.5 0]);
grid on; axis([100 10^5 -160 -70]);
return

Best Answer

This works for me:
fidi = fopen('monkey_matlab sim_data.txt', 'rt');
D = textscan(fidi, '%f%f', 'CollectOutput',1, 'Delimiter','\t');
v = D{:};
% Frequency vector
freq = v(:,1);
% Phase noise vector
pnoise = v(:,2);
subplot(1, 2, 1);
semilogx(freq,pnoise); grid on; axis([100 10^5 -160 -70]);
title('Original Plot');
xlabel('Frequency (Hz)'); ylabel('Amplitude');
subplot(1, 2, 2);
semilogx(freq,pnoise)
grid on; axis([0 10^5 -160 -70]);
hold on
title('Plot with Area Shaded');
xlabel('Frequency (Hz)'); ylabel('Amplitude');
idx=freq>300&freq<3000;
minpnoise = pnoise(find(idx,1,'last'));
patch([300 freq(idx)' 3000 300], [-160 pnoise(idx)' -160 -160], [1 0.5 0]);
grid on; axis([100 10^5 -160 -70]);
Note that your previous code used row vectors. Your data here are column vectors, so you have to transpose them in the patch call. Note the transpose operators (') on ‘freq(idx)’ and ‘pnoise(idx)’ in this line:
patch([300 freq(idx)' 3000 300], [-160 pnoise(idx)' -160 -160], [1 0.5 0]);
That’s the only change you need to make to produce this plot: