count number of elements for each slice of a vector

조회 수: 1 (최근 30일)
LH
LH 2024년 7월 10일
댓글: LH 2024년 7월 10일
Hi all,
I have the folloiwng vector:
A = [2 1;
3 1;
4 2;
5 2;
6 2;
7 1;
8 1 ;
7 1;
5 2;
6 2];
You can see that the second column is either 1 or 2. I would liek to count the slices that has the same number without repetition, meaning that I want to count the first two number that have number 1 in their second column seprately from the three down the vectro (each slice separatly). As a result I wouldl ike to have something like:
num = [2 3 3 2];
Any help would be appreicted.
Thanks.

채택된 답변

Aquatris
Aquatris 2024년 7월 10일
Here is one simple way:
A = [2 1;
3 1;
4 2;
5 2;
6 2;
7 1;
8 1;
7 1;
5 2;
6 2];
tmp = find(diff(A(:,2))~=0); % find indeces where 2nd column values change
num = [tmp(1) diff(tmp') size(A,1)-tmp(end)] % desired output
num = 1x4
2 3 3 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by