Bin average the profile data 1 m vertical average bins

close all
clear all
% Load data for profile 2
load profile2.mat
% Extract the measurement depths, temp and salinity into a vector
% "Depths","Temp", and "Salt"
Depth = depth_profile2;
Temp = temp_profile2;
Salt = sal_profile2;
%% Bin averaging
bin = 1; % bin size in meters
maxDepth = max(Depth);
minDepth = min(Depth);
binDepth = (minDepth:bin:maxDepth)'; % Sequence of depth bins
% bin vectors
bin_vec1 = round(minDepth):bin:round(maxDepth);
bin_vec2 = round(minDepth)+1:bin:round(maxDepth)+1;
M = length(Depth); % number of elements
binTemp = zeros(1,length(bin_vec1)); % zero vector
binSalt = zeros(1,length(bin_vec1)); % zero vector
for kk = 1:length(bin_vec1)
for ii = 1:M
if (Depth(ii) >= bin_vec1(kk)) & (Depth(ii) < bin_vec2(kk)) % assign depth to bins
binTemp(kk) = mean(Temp(ii));
binSalt(kk) = mean(Salt(ii));
end
end
end
% Plot the original profile with the bin average profile
clf
subplot(1,2,1)
plot(Temp,Depth,'linewidth',2)
hold on
plot(binTemp(1:end-1),binDepth,'linewidth',2)
ylabel('Depth [m]')
xlabel('Temperature [deg. C]')
legend('original','bin averaged','location','southwest')
xlim([-2.5 3])
set(gca,'ydir','reverse','linewidth',2,'fontsize',20)
subplot(1,2,2)
plot(Salt,Depth,'linewidth',2)
hold on
plot(binSalt(1:end-1),binDepth,'linewidth',2)
ylabel('Depth [m]')
xlabel('Salinity [ppt]')
xlim([23 35])
set(gca,'ydir','reverse','linewidth',2,'fontsize',20)
% Estimate as a first metric the freshwater component
S_r = 34.8;
F = sum((S_r-binSalt)./S_r)
F = 14.2497