# How to separate a vector into bins and average each bin

32 visualizaciones (últimos 30 días)
Holmbrero el 1 de Ag. de 2022
Comentada: Holmbrero el 1 de Ag. de 2022
I have a vector A (exemplified below) which contains the size of pores and i want to create a vector which bins the data in A and creates a new vector containing the number of pores within a bin size multiplied by the size of these pores (for example by taking the average out of the values within each bin)
Example:
A = [1 1 1 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 6 6 7 7 7 8 9 10]
Lets say that i want the bin size to be 2, then i want something like:
B = [12 32 22 29 19]
Any suggestions would be greatly appriciated.
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Cris LaPierre el 1 de Ag. de 2022
I don't exactly follow how you get from A to B, and I'm fairly certain there isn't a single function that will get you what you want. Here's one possible solution based on what I understood.
A = [1 1 1 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 6 6 7 7 7 8 9 10];
% Use discretize to split the data into bins with width of 2
b = discretize(A,1:2:11)
b = 1×28
1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 4 4 4 4 5 5
% Use splitapply to calculate the mean of each bin
mn = splitapply(@mean,A,b)
mn = 1×5
1.3333 3.5556 5.5000 7.2500 9.5000
% use splitapply to count the number of points in each bin
cnt = splitapply(@numel,A,b)
cnt = 1×5
9 9 4 4 2
% multiply the mean and the count to get B
B = mn.*cnt
B = 1×5
12 32 22 29 19
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Holmbrero el 1 de Ag. de 2022
That does exactly what i asked for. Thank you very much!

Iniciar sesión para comentar.

### Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

R2018b

### Community Treasure Hunt

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

Start Hunting!

Translated by