Count how many times two numbers occur together
조회 수: 3 (최근 30일)
이전 댓글 표시
Hi, I am new to matlab and know this is probably an easy thing to program, but I am still learning and am having some trouble.
I have two columns of values and I want to focus on the second column (e.g., [1,1; 1,1; 2,1; 1,0; 2,1] )
The first thing I want to do is count how many times a 1 is preceeded by a 1 (e.g., in the example above there are two occurances where a 1 was preceeded by a 1)
The first row cannot work with this, so I also want to add 1 to the count if the first row is a 1 (in this example the total would actually be 3)
댓글 수: 0
채택된 답변
Image Analyst
2021년 3월 12일
Try this:
m = [1,1; 1,1; 2,1; 1,0; 2,1]
indexes = strfind(m(:, 2)', [1, 1])
count = length(indexes)
m =
1 1
1 1
2 1
1 0
2 1
indexes =
1 2
count =
2
댓글 수: 4
Image Analyst
2021년 3월 16일
That's easy with regionprops() - just ask for the Area:
m = [1,1; 1,1; 2,1; 1,0; 2,1]
indexes = strfind(m(:, 2)', [1, 1])
count = length(indexes)
% Find 1's in second column of m
oneInCol2 = m(:, 2) == 1
% Get the lengths of all the groups of 1's
props = regionprops(oneInCol2, 'Area');
allRegionLengths = [props.Area]
% Get mean of all the lengths
meanRegionLength = mean(allRegionLengths)
You'll see
oneInCol2 =
5×1 logical array
1
1
1
0
1
allRegionLengths =
3 1
meanRegionLength =
2
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!