extract elements and build the remain vector

Hello Community,
i need your help.
A vector v has 128 elements with random numbers.
The elements of index 1 21 31 41 should be etracted, and saved as vector a.
the remain elements of vector v should be saved as vector b.
my version consist two for loops which is in deed a bad solution for large vectors.
PS: the vectors are not constant.
maybe someone could finish the algorithm:
v = 1:128;
a = v([1 21 31 41]);

 採用された回答

Image Analyst
Image Analyst 2020 年 12 月 21 日

2 投票

Use setdiff():
N = 1600;
v = 1:N;
a = [2 59 87 113]
extracted = v(a)
otherIndexes = setdiff(1:length(v), a);
b = v(otherIndexes)

1 件のコメント

Marko
Marko 2020 年 12 月 21 日
Perfect!
A nice code snippet!

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

その他の回答 (1 件)

David Hill
David Hill 2020 年 12 月 21 日

1 投票

a=v([1 21 31 41]);
b=v([2:20,22:30,32:40,42:end]);

5 件のコメント

Marko
Marko 2020 年 12 月 21 日
編集済み: Marko 2020 年 12 月 21 日
Hello David,
thank you for your fast response. I'm sorry for beeing not specfic enough.
Could you develop a code snippet also for non-constant vectors v,a ?
Best,
MJ
David Hill
David Hill 2020 年 12 月 21 日
Depending on what random numbers you want, use rand() or randi() functions (assuming uniform distribution)
v=A*rand(1,128)-B;%generates random numbers between -B:A-B
Marko
Marko 2020 年 12 月 21 日
ok, i see i was not clear enough.
i try beeing a precicsly as possible:
Vector v has N elements:
N = 1600;
v = 1:N;
Vector a is given and contains integer number: e.g.
a = [2 59 87 113]
How could an algorithm extract a from v and save the remaining elements in vector b.
Important: the vectors v and a have not a constant number of elments, they can change.
The solution should be for this example:
b=[1 3 ... 58 60 ... 86 88 ... 112 114 ... 1600]
David Hill
David Hill 2020 年 12 月 21 日
b=v(~ismember(v,a));
Marko
Marko 2020 年 12 月 21 日
Perfect!
You are a genius!

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

カテゴリ

ヘルプ センター および File ExchangeGet Started with MATLAB についてさらに検索

タグ

質問済み:

2020 年 12 月 21 日

コメント済み:

2020 年 12 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by