How to find index in a single array?

4 ビュー (過去 30 日間)
J Yadav
J Yadav 2019 年 1 月 7 日
コメント済み: J Yadav 2019 年 1 月 8 日
Hi,
I have two column vectors A=(3, 4, 6, 9, 12, 34, 56, 99, 105, 190)' and B=(4, 12, 34, 56)' both are sorted in increasing order. And a bbig matrix D of size mxn, where m is no. of rows in A.
Purpose: is to divide the matrix D into two segments ,
a) matrix E which has 4 rows (=number of rows in B) which are the 2nd, 5th, 6th.. rows of matrix D
and
b) matrix F which has 6 rows (= numbers of rows in A minus number of rows in B) which are 1st, 3rd, 4th, 6th, ...etc rows of D,
So basically the row numbers given bby A has to divided into B and notB.
Here's what I am doing:
I need to find out the placement of each element of B in A. So I am using :
for i=size(B,1)
C(i,1) = find(B(i,1)==A)
end
Question 1: Is there a way to vectorise this process and avoid the LOOP
After that I want to locate the row indexed by B and not B in a mXn matrix D, so I am using
rowEindex=1
rowFindex=1
for j=1:size(B,1)
if A(j,1)==B
E(rowEindex,:) = D(j,:)
rowEindex = rowEindex+1
else
E(rowFindex,:) = D(j,:)
rowFindex = rowFindex+1
end
Question 2: Is there a way to speed up this process, again without using the LOOP
many thanks for your response.

採用された回答

Stephen23
Stephen23 2019 年 1 月 8 日
編集済み: Stephen23 2019 年 1 月 8 日
Simpler:
A = [3;4;6;9;12;34;56;99;105;190];
B = [4;12;34;56];
D = randi(999,200,7); % fake data
E = D(B,:);
F = D(setdiff(A,B),:);
  3 件のコメント
Stephen23
Stephen23 2019 年 1 月 8 日
@SHUBHAM GUPTA: you are right, I fixed that now.
J Yadav
J Yadav 2019 年 1 月 8 日
I have changed the question slightly, bbut your answer to use setdiff is helpful. Thanks,

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

その他の回答 (1 件)

Shubham Gupta
Shubham Gupta 2019 年 1 月 8 日
Try this :
A=[3, 4, 6, 9, 12, 34, 56, 99, 105, 190]';
B=[4, 12, 34, 56]' ;
D=[1:200;1:200;1:200;1:200]';
[val,ind]=intersect(A,B);
E=D(val,:);
A(ind)=[];
F=D(A,:);
I hope this helps.
  1 件のコメント
J Yadav
J Yadav 2019 年 1 月 8 日
I have changed the question slightly, bbut your answer to use intersect is helpful. Thanks,

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by