Extracting elements from a matrix

2 ビュー (過去 30 日間)
Lenilein
Lenilein 2020 年 6 月 14 日
コメント済み: Lenilein 2020 年 6 月 15 日
Hello,
I have a column matrix A with 50 elements and a small column matrix B with 5 elements. I would like to determine the values of the 5 indices i of A for which the value of A(i) is equal to one of the 5 elements of B.
Then there is a column matrix C with 50 elements and I would like to extract all elements of C for the indices determined above in a new matrix D (of 5 elements).
Can someone show me a good way to perform these operations?
I tried to set up a for-loop to go through every single element of A but I don't know how to express that A(i) should be equal to any of the elements of B (in the nested if-loop). Also I am not sure of the best is to save the obtained indices in a new matrix for extracting elements from C.
Many thanks!
  1 件のコメント
KSSV
KSSV 2020 年 6 月 14 日
Read about ismember.

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

採用された回答

KSSV
KSSV 2020 年 6 月 14 日
% Random data for demo
A = rand(50,1) ;
B = A(randperm(50,5)') ; % select five elements of A randomly
C = rand(50,1) ;
[c,ia] = ismember(A,B) ; % get the indices of B in A
D = C(c) ;
  1 件のコメント
Lenilein
Lenilein 2020 年 6 月 15 日
Thank you, it was very helpful!
From what I read in documentation, the answer in your example should be:
[c,ia] = ismember(B,A) ; % get the indices of B in A
D = C(ia) ;

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by