필터 지우기
필터 지우기

Count how many times two numbers occur together

조회 수: 3 (최근 30일)
Millie Johnston
Millie Johnston 2021년 3월 12일
댓글: Image Analyst 2021년 3월 16일
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)

채택된 답변

Image Analyst
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
Millie Johnston
Millie Johnston 2021년 3월 16일
Thanks for pointing the reputation points!
I have anothe question similar to the one I have already asked here, so thought I might try ask it in this thread.
How would I calculate the average number of 1s occuring together in the second col?
Image Analyst
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by