Count how many times two numbers occur together
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Millie Johnston
am 12 Mär. 2021
Kommentiert: Image Analyst
am 16 Mär. 2021
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 Kommentare
Akzeptierte Antwort
Image Analyst
am 12 Mär. 2021
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 Kommentare
Image Analyst
am 16 Mär. 2021
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!