random vector containing zero and values

1 回表示 (過去 30 日間)
meh alipoo
meh alipoo 2016 年 11 月 15 日
コメント済み: meh alipoo 2016 年 11 月 15 日
I have an problem: I have a vector A with size N; I want to fill it up with a random vector with values from [1 randi(N)] while the other elements of A be zero. for example:
N = 6;
A(1:6)=0;
b = randi(N);
C =randperm(b);
now without any loop assign each element of C to the random positions of A while the other un-assigned elements of A remain zero if b<N;

採用された回答

Adam
Adam 2016 年 11 月 15 日
a = zeros(1,6);
n = 6;
b = randi(n);
c = 1:b;
a( randperm( numel(a), b ) ) = c;

その他の回答 (1 件)

Alexandra Harkai
Alexandra Harkai 2016 年 11 月 15 日
A(1:6)=0;
N = 6;
b = randi(N);
C =(1:b);
A_idx = randperm(N, b); % generate b random integers from 1 to N
C_idx = randperm(b); % generate a random permutation of integers from 1 to b
A(A_idx) = C(C_idx); % assign values according to the indices
  2 件のコメント
Alexandra Harkai
Alexandra Harkai 2016 年 11 月 15 日
I realised I over-complicated this by making it random in A and C, but there's no need to. :)
meh alipoo
meh alipoo 2016 年 11 月 15 日
This is also the answer. Thank you.

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by