How to compare the first column of the rows to whole matrix?

1 vue (au cours des 30 derniers jours)
Cagri
Cagri le 23 Oct 2014
Modifié(e) : Guillaume le 24 Oct 2014
I am trying to compare the first columns of rows to whole matrix, and try to find how many times each value occur in the matrix. For example, let
A = [2 4 6 1;
3 7 18 24;
4 2 6 0;
5 8 12 17;
6 2 4 0;
7 3 18 24];
I want to find how many times the row values [2 3 4 5 6 7] occur in the matrix. I can easily find it using for loop, but I don't want any loop. I am also not good at using arrayfun. Can somebody help me?
Thanks.

Réponse acceptée

Guillaume
Guillaume le 23 Oct 2014
From the example, I assume that you want to find the occurrence of the numbers anywhere in the matrix, not just in the same row.
Just use histc or in 2014b, the new histcounts. Use sort or better unique to create your histogram bins:
bins = unique(A(:, 1)); %get unique values of 1st column, sort works if you're sure they're all different
dist = histcounts(A(:, 2:end), bins); get histogram of columns 2 to end
  1 commentaire
Ced
Ced le 23 Oct 2014
Didn't know about histcounts, that's elegant!

Connectez-vous pour commenter.

Plus de réponses (2)

Roger Stafford
Roger Stafford le 24 Oct 2014
Modifié(e) : Roger Stafford le 24 Oct 2014
C = sum(bsxfun(@eq,A(:,1),A),2)-1; % <-- Counts (not counting column 1)
  1 commentaire
Guillaume
Guillaume le 24 Oct 2014
Modifié(e) : Guillaume le 24 Oct 2014
That only counts the occurrence of the number in the same row. I don't think that's what the OP intended, as in the example given, it's always 0.

Connectez-vous pour commenter.


Andrei Bobrov
Andrei Bobrov le 24 Oct 2014
C = sum(bsxfun(@eq,A(:,1),reshape(A,1,[])),2);

Catégories

En savoir plus sur Creating and Concatenating 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!

Translated by