Create binary matrix in Matlab reporting increasing number of ones

丶灬走出姿态 提交于 2020-08-08 06:55:50

问题


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 have 1 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 row

  • from 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:

  1. Generate all possible rows containing zeros and ones, except all zeros or all ones;
  2. Sort rows (atomically) based on row sums, then on negated row values, to produce the desired order;
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!