Counting the number of elements that match between a vector and a matrix
1 view (last 30 days)
Show older comments
Natalie Culhane
on 19 Dec 2014
Edited: Andrei Bobrov
on 19 Dec 2014
I'm looking to count the number of elements that match between a vector and a matrix. I've used the code below:
K= magic(10);
vec=[0 3 7 9 11];
for i= 1:length(vec),
sum(sum(K==vec(i))),
end
This keeps giving me a string of "ans=1" values, rather than the total number of elements that match up (It should be 4 that match). What can I change?
0 Comments
Accepted Answer
Andrei Bobrov
on 19 Dec 2014
nnz(ismember(K,vec))
3 Comments
Andrei Bobrov
on 19 Dec 2014
Edited: Andrei Bobrov
on 19 Dec 2014
Hi Natalie!
variant without nnz :
sum(ismember(K(:),vec)) % corrected after comment by Azzi
More Answers (0)
See Also
Categories
Find more on Fixed-Point Math Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!