- 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 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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:
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!