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

3 次查看(过去 30 天)
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?

采纳的回答

Image Analyst
Image Analyst 2017-12-21
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

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by