MATLAB Answers

How to check if a column data is equal to any of a group of values?

2 ビュー (過去 30 日間)
Leon
Leon 2020 年 10 月 3 日
編集済み: madhan ravi 2020 年 10 月 3 日
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
Sulaymon Eshkabilov 2020 年 10 月 3 日
Hi,
Ind = sum(Ind1) + (Ind2);

  1 件のコメント

Leon
Leon 2020 年 10 月 3 日
Thanks!
Is there a better way to do this? B has an unknown number of elements, not necessarily 2.

サインインしてコメントする。


Sulaymon Eshkabilov
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 件のコメント

Leon
Leon 2020 年 10 月 3 日
Thank you. Unfortunately, it did not work. Were you trying to ask me to do something like this?
for i=1:numel(B)
Ind(:,i) = A==B(i);
end
S = sum(Ind,2);
The problem is that after we sum the logical valeus, I get this error. It seems the function sum messed it up.
Array indices must be positve integers or logical values.
Anyone knows how to find the indices without writing a loop? Many thanks.
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2020 年 10 月 3 日
You have edited the code that I've provide incorrectly.

サインインしてコメントする。


Sulaymon Eshkabilov
Sulaymon Eshkabilov 2020 年 10 月 3 日
Altenrative (more efficient one) solution can be this one:
S = sum(sum(ismember(A,B)))

  0 件のコメント

サインインしてコメントする。


madhan ravi
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 件のコメント

サインインしてコメントする。

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by