Counting the number of elements that match between a vector and a matrix

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?

 채택된 답변

nnz(ismember(K,vec))

댓글 수: 3

comment by Natalie Culhane (copy):
Perfect, thank you. Is there an alternative to using nnz?
Hi Natalie!
variant without nnz :
sum(ismember(K(:),vec)) % corrected after comment by Azzi

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Sparse Matrices에 대해 자세히 알아보기

질문:

2014년 12월 19일

편집:

2014년 12월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by