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)

采纳的回答

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