How to generate square zero one matrix with specific characteristics

1 回表示 (過去 30 日間)
Hayam Wahdan
Hayam Wahdan 2016 年 1 月 16 日
回答済み: BhaTTa 2024 年 7 月 26 日
How to generate square zero one matrix to satisfy this condition ( number of ones/ number of rows ^2)=0.7 or 0.6,.... Any number from 0 to 1

回答 (1 件)

BhaTTa
BhaTTa 2024 年 7 月 26 日
To generate a square matrix of zeros and ones such that the proportion of ones to the total number of elements is a specified value (e.g., 0.7 or 0.6), you can follow these steps in MATLAB:
  1. Determine the size of the matrix. Let's say you want an n×nn \times nn×n matrix.
  2. Calculate the total number of elements in the matrix, which is n2n^2n2.
  3. Determine the number of ones required based on the proportion. For a proportion ppp, the number of ones should be round(p×n2)\text{round}(p \times n^2)round(p×n2).
  4. Generate a matrix with the required number of ones and zeros.
  5. Randomly shuffle the elements to ensure the ones and zeros are randomly distributed.
Here's a MATLAB script that accomplishes these steps:
function matrix = generateBinaryMatrix(n, proportion)
% Input:
% n - Size of the square matrix (n x n)
% proportion - Desired proportion of ones (between 0 and 1)
% Calculate the total number of elements
totalElements = n^2;
% Calculate the number of ones needed
numOnes = round(proportion * totalElements);
% Create a vector with the required number of ones and zeros
matrixVector = [ones(1, numOnes), zeros(1, totalElements - numOnes)];
% Shuffle the vector to randomize the placement of ones and zeros
shuffledVector = matrixVector(randperm(totalElements));
% Reshape the vector into an n x n matrix
matrix = reshape(shuffledVector, n, n);
end
% Example usage:
n = 5; % Size of the matrix
proportion = 0.7; % Proportion of ones
binaryMatrix = generateBinaryMatrix(n, proportion);
% Display the matrix
disp(binaryMatrix);

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by