Finding rows in a matrix

1 Ansicht (letzte 30 Tage)
Sam Da
Sam Da am 6 Okt. 2012
I have a matrix A = [1 2; 2 1; 1 2; 2 2; 1 1; 2 2]
I want to count how many times the row [1 2] appears in above matrix A. Here for my counting purpose [1 2] would appear 3 times as [1 2] or [2 1].
Thanks guys

Akzeptierte Antwort

Matt Fig
Matt Fig am 6 Okt. 2012
Bearbeitet: Matt Fig am 7 Okt. 2012
Another:
% The given matrix
A = [1 2; 2 1; 1 2; 2 2; 1 1; 2 2];
% Now find the counts.
[I,J,K] = unique(sort(A,2),'rows'); % I has the unique rows.
C = histc(K,1:max(K)); % This has the corresponding counts.
% Now that we have found the counts, display them:
fprintf('Row [%i %i] appears %i times. \n',[I C]')
If you want to only get the counts for the one type, this will do it quickly:
cnt = sum(all(bsxfun(@eq,sort(A,2),[1,2]),2));

Weitere Antworten (2)

Azzi Abdelmalek
Azzi Abdelmalek am 6 Okt. 2012
Bearbeitet: Azzi Abdelmalek am 6 Okt. 2012
A = randi(2,10,2)
idx=find(any(repmat([1 2],size(A,1),1)-sort(A,2),2)==0)

Image Analyst
Image Analyst am 6 Okt. 2012
Here's a brute force approach:
A = [1 2; 2 1; 1 2; 2 2; 1 1; 2 2]
sortedA = sort(A, 2)
uniqueRows = unique(sortedA, 'rows')
counts = zeros(1, size(uniqueRows, 1)); % Preallocate.
for row = 1 : size(uniqueRows, 1)
for rowA = 1 : size(A, 1)
matches = sortedA(rowA, :) == uniqueRows(row, :);
if all(matches)
counts(row) = counts(row) + 1;
end
end
end
counts
In the command window:
A =
1 2
2 1
1 2
2 2
1 1
2 2
sortedA =
1 2
1 2
1 2
2 2
1 1
2 2
uniqueRows =
1 1
1 2
2 2
counts =
1 3 2

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by