How can I calculate average values of one data according to specific indexes of same size?

Hi all,
I am intending to calculate average values of density(832695x1 double) according to depth indexes(832695x1 double), in order to obtain one single value of density for each 1 unit depth - elucidated by the table below.
I tried to find a solution applying the following loop; however the results have been not what I was expecting.
if depth_ind=round(depth);
for i=1:1:length(dens)-8
if depth_ind(i)==depth_ind(i+8)
M(i)=(dens(i)+dens(i+1)+dens(i+2)+dens(i+3)+dens(i+4)+dens(i+5)+dens(i+6)+dens(i+7)+dens(i+8))/9;
elseif depth_ind(i)==depth_ind(i+7)
M(i)=(dens(i)+dens(i+1)+dens(i+2)+dens(i+3)+dens(i+4)+dens(i+5)+dens(i+6)+dens(i+7))/8;
elseif depth_ind(i)==depth_ind(i+6)
M(i)=(dens(i)+dens(i+1)+dens(i+2)+dens(i+3)+dens(i+4)+dens(i+5)+dens(i+6))/7;
elseif depth_ind(i)==depth_ind(i+5)
M(i)=(dens(i)+dens(i+1)+dens(i+2)+dens(i+3)+dens(i+4)+dens(i+5))/6;
elseif depth_ind(i)==depth_ind(i+4)
M(i)=(dens(i)+dens(i+1)+dens(i+2)+dens(i+3)+dens(i+4))/5;
elseif depth_ind(i)==depth_ind(i+3)
M(i)=(dens(i)+dens(i+1)+dens(i+2)+dens(i+3))/4;
elseif depth_ind(i)==depth_ind(i+2)
M(i)=(dens(i)+dens(i+1)+dens(i+2))/3;
elseif depth_ind(i)==depth_ind(i+1)
M(i)=(dens(i)+dens(i+1))/2;
else
M(i)=dens(i);
end
end
How could I do that properly?
Thank you for your time,

 Réponse acceptée

X = [1 1021.714
1 1021.726
2 1021.736
2 1021.743
2 1021.749
2 1021.755
2 1021.760
2 1021.765
3 1021.770
3 1021.774
3 1021.778
3 1021.781
3 1021.783
3 1021.787
3 1021.790];
ind = find(diff(X(:,1)) > 0);
ind1 = [1; ind+1];
ind2 = [ind; size(X,1)];
m = [];
for i=1:size(ind1)
ind = ind1(i):ind2(i);
m = [m; repmat(mean(X(ind, 2)), numel(ind), 1)];
end

2 commentaires

Sorry, I forgot to mention the cyclic nature of the depth index variation, the sensor collect data until the max depth and returns to the surface (according to the figure below). Because of that a error occurs associated to upward depths when applying the previous commands.
Thanks for the support,
Try
ind = find(diff(X(:,1)) ~= 0);
If this doesn't work, please provide a sample file that generates the error.

Connectez-vous pour commenter.

Plus de réponses (1)

n = xlsread('path_and_name_your_file_data.xlsx');
out1 = accumarray(n(:,1),n(:,2),[],@mean);
out = [n(:,1),out1(n(:,1))];

1 commentaire

Thanks for you answer Andrei. However, my intention is to produce the mean of just the two indexes of 1 unit depth (for example), not a same density mean for all index of 1 unit depth. The idea is to process the mean of each group separately, the data is relatively big (832695x1 double), and the same depth indexes appears frequently, but irregularly. In other words, I am trying to calculate the mean density just using consecutive identical depth index.
Kind regards,

Connectez-vous pour commenter.

Catégories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by