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

1 vue (au cours des 30 derniers jours)
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?

Réponse acceptée

Image Analyst
Image Analyst le 21 Déc 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

Plus de réponses (1)

James Tursa
James Tursa le 21 Déc 2017
E.g.,
result = rand(10,10) < p;

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!

Translated by