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

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Image Analyst
Image Analyst il 21 Dic 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

Più risposte (1)

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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by