# How may I calculate the number of rows in each group?

11 visualizaciones (últimos 30 días)
Julia el 13 de Feb. de 2023
Comentada: Julia el 13 de Feb. de 2023
Hi! If I have a matrix:
M= [1 50 60 70 50 40
2 NaN 10 20 10 10
3 NaN 20 NaN NaN NaN
1 NaN 60 30 40 50
2 10 20 10 20 NaN
1 30 20 40 NaN 50
2 NaN 50 50 NaN NaN]
The first column indicates to which group the rows belong to. "1, 2, 3" (row 1, 2, 3) are Group 1, "1, 2" (row 4, 5 ) are Group 2, the next "1, 2" ( row 6, 7) are Group 3.
I am trying to find the number of rows in each group. The desired result would be:
N= [3
2
2]
Could someone please teach me how to do this? It seems that I can't get my head around it. I think the first step can be splitting the groups:
g=nan(size(M,1),1);
ix=(M(:,1)==1);
g(ix)=[1:sum(ix)];
g=fillmissing(g,'previous');
but I am not sure where to go from here.
##### 2 comentariosMostrar NingunoOcultar Ninguno
KSSV el 13 de Feb. de 2023
Whats the logic for this?
"1, 2, 3" (row 1, 2, 3) are Group 1, "1, 2" (row 4, 5 ) are Group 2, the next "1, 2" ( row 6, 7) are Group 3
Dyuman Joshi el 13 de Feb. de 2023
Editada: Dyuman Joshi el 13 de Feb. de 2023
So when the value in first column is 1, a new group starts? If so, @Voss's answer should be good to go.
If not, then specify a general criteria for splitting into groups.

Iniciar sesión para comentar.

Voss el 13 de Feb. de 2023
diff(find([M(:,1); 1] == 1))
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Julia el 13 de Feb. de 2023

Iniciar sesión para comentar.

### Más respuestas (1)

Bhavana Ravirala el 13 de Feb. de 2023
Hi Julia,
According to my understanding, the first element of the row is deciding the group. You can use the below code to know the number of rows in each group.
N=M(:,1); % getting the first column of elements which we are using to divide the groups
k=length(N); % gives the number of rows in the matrix
j=[];
o=0;
for i=1:k
if(n(i)==1)
if(o~=0)
j=[j,o];
end
o=1;
else
o=o+1;
if i==k
j=[j,o];
end
end
end
Hope this helps!!
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Julia el 13 de Feb. de 2023
Thank you! I'll look into the use of for loop.

Iniciar sesión para comentar.

### Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by