필터 지우기
필터 지우기

Creating a Matrix of random numbers

조회 수: 11 (최근 30일)
Blair Hail-Brown
Blair Hail-Brown 2020년 11월 21일
답변: venkata datta sai krishna 2022년 11월 25일
I'm trying to create a 20x20 matrix of values either -1 or 1, but randomly assigned. How can i do this? I've tried using the randi function but it returns the numbers as a range from -1 1 and so includes 0. any help would be appreciated

채택된 답변

Steven Lord
Steven Lord 2020년 11월 21일
possibleValues = [-1, 1];
desiredSize = [5 6];
A = possibleValues(randi(numel(possibleValues), desiredSize))
A = 5×6
-1 1 1 1 1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 1 -1 -1 1 1 -1 1 1 -1 -1 1 -1 1 1 -1
This assumes you want -1 and 1 to be equally likely. If you need an exact number of each possible value:
elements = [repmat(-1, 1, 5), repmat(1, 1, 25)];
order = randperm(numel(elements));
shuffled = reshape(elements(order), desiredSize)
shuffled = 5×6
1 -1 1 1 1 1 1 1 1 1 -1 1 1 1 -1 1 1 1 -1 1 1 1 1 1 -1 1 1 1 1 1
If you need the two numbers not to be equally likely (say 1 three times as likely as -1) there are ways to do this as well.
  댓글 수: 1
Blair Hail-Brown
Blair Hail-Brown 2020년 11월 22일
Absolutely perfect, thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (4개)

John D'Errico
John D'Errico 2020년 11월 21일
randi([0 1],20)*2 - 1

David Hill
David Hill 2020년 11월 21일
(-1).^randi(2,20);

Setsuna Yuuki.
Setsuna Yuuki. 2020년 11월 21일
A long way
bits= randi([-1 1],20,20);
[r,c,~] = size(bits);
count = 1;
while count < (r*c)+1
bits = reshape(bits,[1 r*c]);
if(bits(count) == 0)
bits(count) = randi([-1 1],1);
count = 1;
else
count = count + 1;
end
end
bits = reshape(bits,[r c]);

venkata datta sai krishna
venkata datta sai krishna 2022년 11월 25일
create a random integer 4*4 matrix A with rank equals 2(maximum only two columns are independent) and demonstrate above factorisation in matlab

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by