chop array and average
Afficher commentaires plus anciens
Hi!
I have a dataset 1000x10 that the nth colum is an index, i.e. either 0, 1 or 2 but in a non-regular sequence or length. The rest of columns are my data. A simplified example would be:
1 0
2 0
4 1
6 1
7 1
4 2
3 2
1 0
7 0
2 1
5 0
6 0
2 2
Where column 1 is the data and column 2 is the index column.
I would like to average the "blocks" of data where 0-index is continuous and ommit the data with 1 and 2 indexing. Therefore I want to average the data in the first 2 cells, the 8th with the 9th and the 11th with the 12th cell and obtain:
1.5
4
5.5
How to do this in matlab?
Many thanks in advance!
Réponses (2)
Image Analyst
le 8 Jan 2021
You can simply call regionprops() if you have the Image Processing Toolbox.
data = [1 0
2 0
4 1
6 1
7 1
4 2
3 2
1 0
7 0
2 1
5 0
6 0
2 2] ;
% Find out where last column is 0.
mask = data(:, end) == 0;
% Measure mean values there in each region of 0s independently:
props = regionprops(mask, data(:, 1), 'MeanIntensity');
theMeans = [props.MeanIntensity] % Extract from structure array into vector.
If you want to do it over all columns, put into a loop
[~, numRegions] = bwlabel(mask);
numColumns = size(data, 2) - 1 % All columns except the last one.
theMeans = zeros(numColumns, numRegions);
for col = 1 : numColumns
% Measure mean values there
props = regionprops(mask, data(:, col), 'MeanIntensity');
% Store all the means for this column into one row of theMeans.
theMeans(col, :) = [props.MeanIntensity]
end
KSSV
le 8 Jan 2021
data = [1 0
2 0
4 1
6 1
7 1
4 2
3 2
1 0
7 0
2 1
5 0
6 0
2 2] ;
A = zeros(1,size(data,1)) ;
A(data(:,2)==0) = data(data(:,2)==0,1) ;
ii = zeros(size(A));
jj = A > 0;
ii(strfind([0,jj(:)'],[0 1])) = 1;
idx = cumsum(ii).*jj;
out = accumarray( idx(jj)',A(jj)',[],@(x){x'});
iwant = cellfun(@mean,out)
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!