How to check if a column data is equal to any of a group of values?
11 次查看(过去 30 天)
显示 更早的评论
I have a column data A like the below:
A = [1; 3; 2; 7; 11; 6];
B can be a group of numbers with unknow counts. For example B can be like the below:
B = [1; 7];
Here is my question. How do I come up with an index to show the elemens of A that can be any of B? For example if I know B has two elements, I can use something like the below, but B can have an unknown number of elements.
Ind1 = A == B(1);
Ind2 = A == B(2);
Ind = Ind1 + Ind2;
0 个评论
回答(4 个)
Sulaymon Eshkabilov
2020-10-3
You can use a loop for instance if you have many Bs, e.g.:
for ii = 1:numel(B)
Ind = A==B(ii); S(ii) = sum(Ind(:));
end
S_all=sum(S); % Total number of observed cases
2 个评论
Sulaymon Eshkabilov
2020-10-3
Altenrative (more efficient one) solution can be this one:
S = sum(sum(ismember(A,B)))
0 个评论
madhan ravi
2020-10-3
编辑:madhan ravi
2020-10-3
clear sum
Ind = sum(ismember(A, B), 2)
%Or perhaps you need
Ind = nnz(ismember(A, B))
%or
fprintf('%d occurs %d times/s\n', [B.'; sum(A == B.')])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!