フィルターのクリア

how to generate random number at certain entries of a vector

2 ビュー (過去 30 日間)
Vu
Vu 2015 年 9 月 1 日
コメント済み: Vu 2015 年 9 月 1 日
I have a question about generate random number.For example I have a vector of side 10. If I want to use rand() function to generate instantaneously random numbers for only some elements in the vector, how can I do that. Specifically let say I have a defined vector and I only want to apply rand() function only to those entries whose value is smaller than 0.5, which can be found by using find() function.
%% x = rand(10,1); %% ind = find(x<0.5);
THanks, Vu
  2 件のコメント
James Tursa
James Tursa 2015 年 9 月 1 日
What do you mean by "apply rand() function"? Once you find the elements, what do you want to do to them?
Vu
Vu 2015 年 9 月 1 日
I want to generate random number and replace it with the new value

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

回答 (1 件)

Joe
Joe 2015 年 9 月 1 日
Logical indexing is your friend here. You can create a logical mask of elements in your vector which meet the desired criteria. You can then index with that mask, and use its sum (not its size, unfortunately) to generate the appropriate count of random numbers.
% Vector of interest
x = randi(2, 1, 10)/2 - 0.25; % Entries are 0.25 or 0.75
% Generate logical mask
mask = x < 0.5;
% Index random numbers using mask
x(mask) = rand(sum(mask), 1);
The annoying part of this approach is you must make sure your call to "rand()" matches the size of your vector. Another approach is to first generate a random vector of size "x" and index it using "mask," but that wastes time generating numbers you don't need for larger arrays.
  1 件のコメント
Vu
Vu 2015 年 9 月 1 日
I agree. I thought about the second approach but since I am working with stochastic simulation which requires a large number of sample paths so I tried not to generate unless I need it

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by