Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

I want to randomly have numbers added to a matrix

조회 수: 1 (최근 30일)
Daniel Gray
Daniel Gray 2017년 7월 11일
마감: MATLAB Answer Bot 2021년 8월 20일
I have a 300x300 zeros matrix and I want to have numbers between 0 and 1 (inclusive) randomly placed amongst the matrix, the numbers can be repeated (and ideally will be repeated completely randomly). Any help would be great.

답변 (3개)

KSSV
KSSV 2017년 7월 11일
편집: KSSV 2017년 7월 11일
A = round(rand(300,300)) ;
or
A = randi([0 1],300,300)

Star Strider
Star Strider 2017년 7월 11일
Use the randi function:
M = randi([0 1],300);
  댓글 수: 3
KSSV
KSSV 2017년 7월 11일
That case you should use rand
Jan
Jan 2017년 7월 11일
편집: Jan 2017년 7월 11일
X = rand(300, 300);
KSSV and Star Strider have suggested randi and rand already. Although the code did not solve your problem completely, the hints are useful already: Read the documentation of the suggested commands to find out, how to use them such, that it satisfies your need. The "See also" lines on the bottom of the docs are very valuable.
I suggest to use the forum not only as a service for complete solutions, but to consider all details mentioned here to improve your own Matlab skills.
In German this is called "mitdenken", but I cannot translate this to English. It doubles the power of the given answers. :-)

Image Analyst
Image Analyst 2017년 7월 11일
This will do it:
% Create a matrix of all zeros
m = zeros(300, 300);
% Get locations for random changes
% Define the number of random numbers you want placed.
numRandomNumbers = round(.3 * numel(m)); % For example 30%
% Get their locations, randomly arranged.
linearIndexes = randperm(numel(m), numRandomNumbers);
% Assign random numbers to those locations
m(linearIndexes) = rand(1, numRandomNumbers);
imshow(m)

Community Treasure Hunt

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

Start Hunting!

Translated by