I want to convert vector into matrix with all possible combinations

조회 수: 2 (최근 30일)
Owais Rasool
Owais Rasool 2022년 8월 17일
편집: James Tursa 2022년 8월 17일
First I want to create a vector with combinations of 8 ones and 16 zeros, which are generated randomly, representing on and off states of Generator for 24 hours. Then I want to convert the vector into matrix by shuffling the values into all possible combinations of 1 & 0, while one and zero appearing the same 8 and 16 times in each row.

답변 (1개)

James Tursa
James Tursa 2022년 8월 17일
편집: James Tursa 2022년 8월 17일
I think John D'Errico answered this some time ago, or a question very much like this. But I can't find his post at the moment. I think it went something like this:
n = 24; k = 8; % n = total number of bits in a row, k = number of 1's in a row
x = combnk(1:n,k); % Enumerate all the possible spots for the 1's
r = size(x,1); % Total number of rows
b = false(r,n); % Create output with desired size
x = (1:r)' + (x-1)*r; % Turn enumeration into linear indexes
b(x(:)) = true; % Fill the linear index spots with 1's
To pick off a row at random, simply
b(randi(r),:);
CAUTION: Enumerating all possibilities in problems like this can quickly chew up vast amounts of memory. You might exhaust all the RAM in your computer, or the program will take unreasonable amounts of time to process all the rows. I have coded the output as a logical matrix to save space, but still you can easily have problems with this enumerated approach. In such cases a statistical approach will often suffice. I.e., instead of examining all possibilities, run a Monte Carlo simulation of random patterns with a reasonably large number of trials. The random pattern could be generated as follows:
b = false(1,n);
b(randperm(n,k)) = true;

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by