MATLAB: How to construct boot strap confidence band for (x,y ) data

bootstrap confidence band

x = data(:,1);
y= data(:,2);
p = polyfit(x,y,2);
Pv=polyval(p,x);
plot(x,y,'o',x,Pv);
hold on;
nboot=5000;
where I am struggling to do Bootstrap and get bootstrap confidence band for the second order polynomial fit curve I need your help to proceed further
Thank you
Govind

Best Answer

% Made up some data. Use your real data here
rng 'default'
N = 100; % You need this size later in the code to get the right number of resamples.
data = randn(N,2);
x = data(:,1);
y = data(:,2);
% Number of bootstrap samples
NBOOT = 5000;
% I made the 2nd-order polynomial fit more general, using a parameter
POLYNOMIAL_ORDER = 2;
% Fit and plot of original data
% Notice that I sorted the x data before getting "Pv", so then you get the line.
p = polyfit(x,y,POLYNOMIAL_ORDER);
Pv = polyval(p,sort(x));
figure
hold on
plot(x,y,'o',sort(x),Pv);
% Generate NBOOT resamplings of the x-y pairs
resampled_index = randi(N,N,NBOOT);
resampled_x = x(resampled_index);
resampled_y = y(resampled_index);
% Pre-allocate memory for the resampled fit values
p_boot = zeros(NBOOT,POLYNOMIAL_ORDER+1);
Pv_boot = zeros(N,NBOOT);
% Fit each instance of the resampled data
for nb = 1:NBOOT
p_boot(nb,:) = polyfit(resampled_x(:,nb),resampled_y(:,nb),POLYNOMIAL_ORDER);
Pv_boot(:,nb) = polyval(p_boot(nb,:),sort(resampled_x(:,nb)));
end
% Here are the mean bootstrap fit parameters. You can also do other stats such as standard deviation and percentiles to get your confidence bands.
mean_fit = mean(p_boot)