问题
I would like your advise to write a Matlab code that creates a binary matrix A
of size 31x5
such that
the first row of
A
is[1 1 1 1 1]
from the 2nd to the 6th of
A
we have1
only once per row[1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1]
from the 7th to the 16th row we have
1
twice per row[1 1 0 0 0 1 0 1 0 0 1 0 0 1 0 ...]
from the 17th to the 26th row we have
1
three times per rowfrom the 26th to the 31th row we have
1
four times per row
I could that manually, but I would like to know if there is a faster way to proceed.
回答1:
Here's an approach:
- Generate all possible rows containing zeros and ones, except all zeros or all ones;
- Sort rows (atomically) based on row sums, then on negated row values, to produce the desired order;
- Prepend a row of ones to build the result.
N = 5;
A = dec2bin(1:2^N-2)-'0'; % step 1
[~, ind] = sortrows([sum(A,2) -A]); % step 2
result = [ones(1,N); A(ind,:)]; % step 3
回答2:
I recommend you the command bin2dec()/dec2bin() with a for-loop. bin2dec('10000') writes 16 and your next writes bin2dec('01000') 8 so I guess you are following some sort of pattern?
put all of your wanted numbers in an array like that:
clear all;
nums = [16 8 4 2 0];
mat = [];
for(a=1:1:size(nums,2))
mBinChar = dec2bin(nums(a));
for(b=1:1:length(mBinChar))
mat(a,b) = str2double(mBinChar(1));
end
end
来源:https://stackoverflow.com/questions/63113114/create-binary-matrix-in-matlab-reporting-increasing-number-of-ones