How to generate square zero one matrix with specific characteristics

조회 수: 5 (최근 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 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