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

4 ビュー (過去 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
  2 件のコメント
Gaëtan Poirier
Gaëtan Poirier 2017 年 12 月 21 日
how would I be able to print the matrix as a grid? with 1's and 0's being different colors?

サインインしてコメントする。

その他の回答 (1 件)

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by