Creating a Matrix of random numbers
31 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Blair Hail-Brown
le 21 Nov 2020
Réponse apportée : venkata datta sai krishna
le 25 Nov 2022
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
0 commentaires
Réponse acceptée
Steven Lord
le 21 Nov 2020
possibleValues = [-1, 1];
desiredSize = [5 6];
A = possibleValues(randi(numel(possibleValues), desiredSize))
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)
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.
Plus de réponses (4)
Setsuna Yuuki.
le 21 Nov 2020
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]);
0 commentaires
venkata datta sai krishna
le 25 Nov 2022
create a random integer 4*4 matrix A with rank equals 2(maximum only two columns are independent) and demonstrate above factorisation in matlab
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!