- Determine the size of the matrix. Let's say you want an n×nn \times nn×n matrix.
- Calculate the total number of elements in the matrix, which is n2n^2n2.
- 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).
- Generate a matrix with the required number of ones and zeros.
- Randomly shuffle the elements to ensure the ones and zeros are randomly distributed.
How to generate square zero one matrix with specific characteristics
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
BhaTTa
on 26 Jul 2024
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:
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);
0 Comments
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!