Matrix's and percents
Show older comments
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?
Accepted Answer
More Answers (1)
Image Analyst
on 17 Dec 2013
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
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!