How would I go about making a 10 by 10 matrix with only 1,2,and 3's. And having 20% be 1, 40% be 2 and 40% be 3's?

 Réponse acceptée

Honglei Chen
Honglei Chen le 17 Déc 2013
Modifié(e) : Honglei Chen le 17 Déc 2013

0 votes

x = rand(10);
x1 = zeros(10);
x1(x<0.2) = 1;
x1(0.2<=x&x<0.6) = 2;
x1(x>=0.6) = 3;
or if you want precise 20%, 40% and 40%, you can do
x = zeros(10);
k = randperm(100);
x(k(1:20)) = 1;
x(k(21:60)) = 2;
x(k(61:100)) = 3;

2 commentaires

Image Analyst
Image Analyst le 17 Déc 2013
Does not guarantee the 20, 40, 40 percentages - just try it and see.
Honglei Chen
Honglei Chen le 17 Déc 2013
Yes, I realized it, so I updated the answer.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 17 Déc 2013

0 votes

Try this:
m = ones(10, 10) % Create 1's
% Need 40 2's
% Could set to 4 but let's make it more general
numberOf2s = 0.4 * numel(m);
% Get their locations
locationOf2s = randperm(numel(m), numberOf2s);
% Assign them
m(locationOf2s) = 2
% Now need 40 threes, but not where there are already 1s or 2s.
% Could set to 40 but let's make it more general
numberOf3s = 0.4 * numel(m);
% First find locations of 1s. We need to replace some of them
linear1indexes = find(m == 1)
% Get 40 random locations from those
indexesOf3s = randperm(length(linear1indexes), numberOf3s)
% Initialze a logical index array.
locationOf3s = false(length(linear1indexes));
% Set the location where 3s will go to true.
locationOf3s(linear1indexes) = true;
% Set those locations = 3
m(locationOf3s) = 3

Catégories

En savoir plus sur Sparse Matrices dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by