How to select complementary elements from a vector?

64 ビュー (過去 30 日間)
Shadman Shahid
Shadman Shahid 2021 年 4 月 7 日
回答済み: Bruno Luong 2021 年 4 月 20 日
I have a vector
d = [33 20 4 5 6 75 8 9 0];
and another vector containing the indices whose complement i have to select from d.
I = [1 3 7];
so, the output I want is a vector which is - d minus the elements contained in d(I)
i.e
ans = [20 5 6 75 9 0];
  2 件のコメント
John D'Errico
John D'Errico 2021 年 4 月 7 日
Your example is flawed, since 7 is in I.
Shadman Shahid
Shadman Shahid 2021 年 4 月 20 日
編集済み: Shadman Shahid 2021 年 4 月 20 日
No. Its correct, I have changed the values to make the example clearer.
I is the vector of the index.
So, d(I) = [3 1 8];
What I want is to get rid of these elements from d. Not the values [1,3,7]. I is the index of the vector d.

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

採用された回答

Bruno Luong
Bruno Luong 2021 年 4 月 20 日
d = [33 20 4 5 6 75 8 9 0];
I = [1 3 7];
d(setdiff(1:end,I))
ans = 1×6
20 5 6 75 9 0

その他の回答 (4 件)

Bruno Luong
Bruno Luong 2021 年 4 月 7 日
>> d(~ismember(d,I))
ans =
2 5 6 8 9 0

Khalid Mahmood
Khalid Mahmood 2021 年 4 月 7 日
編集済み: Khalid Mahmood 2021 年 4 月 19 日
%Another but lengthy way is as follows:
%Vector 1
d = [3 2 1 5 6 7 8 9 0];
%Another vector containing the indices, which must be removed from d .
I = [1 3 7];
%so, the output is a vector which removes those values, i.e output= [2 5 6 9 0];
n1=size(d,2);
n2=size(I,2);
%A=zeros(1,n1-n2)
k=1;i=1;
for n=1:n1
if n~=I(k)
A(i)=d(n);
i=i+1;
else
if k<n2
k=k+1;
end
end
end
A
%same as A=d(~ismember(d,I))

John D'Errico
John D'Errico 2021 年 4 月 7 日
編集済み: John D'Errico 2021 年 4 月 7 日
d = [3 2 1 5 6 7 8 9 0];
I = [1 3 7];
setdiff(d,I)
ans = 1×6
0 2 5 6 8 9
Note that your example is actually incorrect, in that you claim 7 should be in the final result. But since 7 is a member of I, that is not the case.
Also, it depends on if you want elements that remain in the original order. setdiff will return a sorted set, and if any elements of d were repeated, then only one copy will remain in the result.
So if setdiff does not do as you wish, in that case, you need to use ismember, deleting the elements found. Thus...
d(~ismember(d,I))
ans = 1×6
2 5 6 8 9 0

Bruno Luong
Bruno Luong 2021 年 4 月 20 日
d = [33 20 4 5 6 75 8 9 0];
I = [1 3 7];
d(I) = []
d = 1×6
20 5 6 75 9 0

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by