How can I create a matrix of black and white blocks given probability p of being black or white?

10 views (last 30 days)
I want to create a 10x10 matrix of 0's. There is a probability p of the 0 becoming a 1. If the block is a 1, the block is black, if 0, the block is white.
I don't really know how to iterate this:
I assume I would start with the given matrix. I would use
zeros(10,10)
and then iterate through using random numbers
if p<0.5 % I don't know how to change from 0 to 1
then how would I visualize the matrix in the colors?
Thank you for and help?

Accepted Answer

Image Analyst
Image Analyst on 21 Dec 2017
Try this:
% Define parameters.
rows = 10;
columns = 10;
percentage = 0.5;
% Create initial matrix of all zeros.
m = zeros(rows, columns)
% Figure out how many elements need to be set to 1.
numIndexes = round(percentage * rows*columns)
% Use randperm() to get that number of elements from random locations:
indexesToSet = randperm(rows*columns, numIndexes)
% Set those indexes to 1
m(indexesToSet) = 1

More Answers (1)

James Tursa
James Tursa on 21 Dec 2017
E.g.,
result = rand(10,10) < p;

Categories

Find more on Creating and Concatenating Matrices 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!