By following codes, I get a 50x50 matrics with randon 1 and 0. Now I want to specify how many 1 and how many 0 are in this 50x50 matrics, and I want them in randon positions.
Thank you very much for your helps!
nside=50;
randworld=round(rand(nside,nside));
world=randworld>.5;

 採用された回答

Image Analyst
Image Analyst 2019 年 12 月 8 日

0 投票

Use randperm:
nside=50;
world = zeros(nside, nside);
num1sToInsert = 4;
randomIndexes = randperm(numel(world), num1sToInsert)
world(randomIndexes) = 1

4 件のコメント

Johnny
Johnny 2019 年 12 月 8 日
Sorry, Im not quite understand.
How ccould I control the amount of 1 and 0 in the world with randperm?
'num1sToInsert = 4',why do we need this?
Thank you for your answer!
per isakson
per isakson 2019 年 12 月 8 日
>> figure, imagesc( world )
displays
Capture.PNG
Notice the four white squares
Image Analyst
Image Analyst 2019 年 12 月 8 日
編集済み: Image Analyst 2019 年 12 月 8 日
Johnny, recall you said "I want to specify how many 1 and how many 0 are", and if you look in the documentation for randperm, the second argument is the number of numbers you want to get and assign 1 to. For example if you have 50-by-50 matrix, then there are 2500 elements in that matrix. So randperm will get a scrambled array of every index from the upper left (index 1) to the lower right (index 2500) - basically all numbers from 1 to 2500 scrambled up, if you don't specify the second argument. If you DO specify a second argument, then it won't return all 2500 - we don't need all 2500 - it will return however many you ask for in the second argument. So let's say you wanted to have 4 1's and 2496 0's. Well
randomIndexes = randperm(numel(world), num1sToInsert)
will return exactly 4 indexes randomly located somewhere within those 2500 elements. This is basically the same as
randomIndexes = randperm(2500, 4) % Return 4 numbers chosen randomly between 1 and 2500.
Then I use those indexes to set the matrix at those indexes to 1.
Johnny
Johnny 2019 年 12 月 8 日
Thank you very much!it is very clear!
Really appreciate for your helps!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2019 年 12 月 8 日

コメント済み:

2019 年 12 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by