Azzera filtri
Azzera filtri

Count how many times two numbers occur together

3 visualizzazioni (ultimi 30 giorni)
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)

Risposta accettata

Image Analyst
Image Analyst il 12 Mar 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 Commenti
Millie Johnston
Millie Johnston il 16 Mar 2021
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 il 16 Mar 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

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by