How to get the opposite elements of a vector specified by an index?

17 ビュー (過去 30 日間)
Stef
Stef 2018 年 4 月 27 日
コメント済み: Rik 2018 年 4 月 27 日
I have a variable s picking 70 random numbers from 0 to 100. Now I want to have all 30 elements of the vector a, which are not in s.
s = randsample(100,70)
I have already tried
z = a(~s)
but that does not work.

採用された回答

Rik
Rik 2018 年 4 月 27 日
randsample picks values from 1 to N, not 0 to N. The first block is for 1:N, the second for 0:N
maxval=100;
s = randsample(maxval,70);
not_s=1:maxval;not_s(s)=[];
maxval=100;
s = randsample(maxval+1,70);
not_s=1:maxval;not_s(s)=[];
not_s=not_s-1;s=s-1;
  2 件のコメント
Stef
Stef 2018 年 4 月 27 日
Thanks! I needed it for the 1:N. Could you please explain the intuition? I do not understand why it picks exactly the opposite ones now
Rik
Rik 2018 年 4 月 27 日
What this code does is generating the vector 1:N and then removing all positions described by s. This makes use of the fact that position and value is the same in the vector that results from 1:N.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by