How does ismember and assert work in this code?

6 ビュー (過去 30 日間)
Masha
Masha 2023 年 2 月 2 日
コメント済み: Voss 2023 年 2 月 3 日
Previously, I raised a question of how to generate a matrix of only masses; provided that a matrix A is given that contains the object list and a matrix B that contains the objects + their masses. I am new to MATLAB and I want to know how the code works. Thank you!
A = ["C"; "A"; "E"; "F"; "I"]
A = 5×1 string array
"C" "A" "E" "F" "I"
B = ["A", 1;"B", 34;"C" 56;"D" 32;"E",11;"F",8;"G", 7;"H",9;"I" 77]
B = 9×2 string array
"A" "1" "B" "34" "C" "56" "D" "32" "E" "11" "F" "8" "G" "7" "H" "9" "I" "77"
[ism,idx] = ismember(A,B(:,1));
assert(all(ism))
result = B(idx,:)
result = 5×2 string array
"C" "56" "A" "1" "E" "11" "F" "8" "I" "77"

採用された回答

Voss
Voss 2023 年 2 月 2 日
[ism,idx] = ismember(A,B(:,1)); returns
  • ism, a logical array the same size as A saying whether each element of A is in B(:,1), i.e., ism is true where the corresponding element of A exists in B(:,1) and ism is false where the corresponding element of A is not in B(:,1)
  • idx, the index in B(:,1) where the first instance of each element of A exists, or 0 if that element of A does not exist in B(:,1)
Examples to illustrate:
x = [10;50;70];
y = [10;30;50;70];
[ism,idx] = ismember(x,y)
ism = 3×1 logical array
1 1 1
idx = 3×1
1 3 4
x = [10;50;70];
y = [10;30;10;30;50;70];
[ism,idx] = ismember(x,y)
ism = 3×1 logical array
1 1 1
idx = 3×1
1 5 6
x = [10;20;70];
y = [10;30;10;30;50;70];
[ism,idx] = ismember(x,y)
ism = 3×1 logical array
1 0 1
idx = 3×1
1 0 6
assert is used in this case to make sure that all elements of A exist in B(:,1). If that's not the case, an error is thrown, execution of the code stops, and subsequent commands are not executed.
assert(all(ism))
Error using assert
Assertion failed.
References:
  2 件のコメント
Masha
Masha 2023 年 2 月 3 日
Thank you!
Voss
Voss 2023 年 2 月 3 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by