How do I create a n by n matrix, randomly filled with only k specific values ; m1,m2,m3..mk where m1, m2, m3..mk are specified
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Tarun Cousik
le 10 Nov 2016
Commenté : James Tursa
le 11 Nov 2016
Example
Say I want a 3 by 5 matrix filled randomly with only 2 particular values 2 and 6
A=
2 6 2 2 6; 6 2 6 6 2; 2 2 6 2 2;
I'm thinking of using a function like Rand and combine it with a round function, any tips/solutions are much appreciated!
-Tarun
0 commentaires
Réponse acceptée
Image Analyst
le 10 Nov 2016
Modifié(e) : Image Analyst
le 10 Nov 2016
Try this:
myNumbers = [2.3, pi] % Whatever
% Find out how many unique numbers there are.
numNumbers = length(unique(myNumbers))
% Create a labeled 3-by-5 matrix with values from 1 to numNumbers
m = randi(numNumbers, 3, 5)
% Now replace each integer label ID of m with the value from myNumbers
for k = 1 : numNumbers
m(m == k) = myNumbers(k);
end
% Print to command window:
m
In the command window you'll see:
myNumbers =
2.3 3.1416
numNumbers =
2
m =
1 2 1 2 2
2 1 1 1 2
1 2 1 1 2
m =
2.3 3.1416 2.3 3.1416 3.1416
3.1416 2.3 2.3 2.3 3.1416
2.3 3.1416 2.3 2.3 3.1416
It's generalizable to any numbers you want to use, not just integers, and any number of rows and columns.
3 commentaires
Image Analyst
le 11 Nov 2016
That's far simpler. Simply use randi():
m = 2 * randi([0,1], 100) - 1
James Tursa
le 11 Nov 2016
If you just want -1 or +1, then see this link:
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!