Counting Specific Number of Consecutive Values in a Matrix
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gabriela Garcia
le 17 Jan 2021
Modifié(e) : Image Analyst
le 17 Jan 2021
I have a matrix composed of ones and zeros.
I need to idenity where there are three 1s in each COLUMN
1 0 0 1 1
1 0 1 1 1
1 1 1 0 1
1 0 1 1 1
1 1 0 1 1
0 1 1 1 1
1 1 1 0 1
I want to have the code identify if
- there are three consecutive 1s in the first through third column, and
- that there are two sets of consecutive 1s in the fourth column.
I then want to compare this matrix with another matrix, and find where they are similar in the exact locations of the three consecutive 1s.
0 commentaires
Réponse acceptée
Image Analyst
le 17 Jan 2021
Here's another way using the Image Processing Toolbox to filter out short sequences and count how many are left:
A = [1 0 0 1 1
1 0 1 1 1
1 1 1 0 1
1 0 1 1 1
1 1 0 1 1
0 1 1 1 1
1 1 1 0 1]
A = logical(A); % Make sure it's logical.
[rows, columns] = size(A)
criteria = false(1, 4); % True or false for whether the criteria for that column is met or not
for col = 1 : 3
% Get rid of any sequences that are not at least 3 long in the first 3 columns.
A(:, col) = bwareaopen(A(:, col), 3);
% Set the criteria
[~, numSequences] = bwlabel(A(:, col)) % Count number of sequences.
criteria(col) = numSequences >= 1
end
% For the 4th column, make sure there are at least 2 sets of 1s
% that are at least 2 elements long.
col4 = bwareaopen(A(:, 4), 2) % Only sequences 2 or longer survive.
[~, numSequences] = bwlabel(col4)
criteria(4) = numSequences >= 2
% Show results in command window
A
criteria
0 commentaires
Plus de réponses (1)
KSSV
le 17 Jan 2021
Modifié(e) : KSSV
le 17 Jan 2021
A = [1 0 0 1 1
1 0 1 1 1
1 1 1 0 1
1 0 1 1 1
1 1 0 1 1
0 1 1 1 1
1 1 1 0 1];
% First column
x = A(:,1) ;
f = find(diff([0 ;x ;0]==1));
id = f(1:2:end-1); % Start indices
N = f(2:2:end)-p; % Consecutive ones’ counts
Also have a look on ismember, this would be useful to check two different matrices have common eements.
0 commentaires
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!