我想在MATLAB中创建一个矩阵,其中:
第一行由0和1的随机排列组成,均匀分割(即50-50)。
第二行随机分配零到第一行中0和1的50%,以及剩余50%中的0。
第三行随机分配零到50%的0和1在第二行,其余为50%。
非随机化示例:
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
有什么建议吗?
答案 0 :(得分:7)
基于检查数字是大于还是小于中位数的解决方案。只要测试的列数是偶数,一组随机双精度的正好一半将大于中位数,一半将更小。这可以保证正好有50%的位被翻转。
nRows = 3;
nCols = 16; %# divisible by 4
%# seed the array
%# assume that the numbers in each row are unique (very, very likely)
array = rand(nRows,nCols);
out = false(nRows,nCols);
%# first row is special
out(1,:) = array(1,:) > median(array(1,:));
%# for the rest of the row, check median for the zeros/ones in the previous row
for iRow = 2:nRows
zeroIdx = out(iRow-1,:) == 0;
%# > or < do not matter, both will replace zeros/ones
%# and replace with exactly half zeros and half ones
out(iRow,zeroIdx) = array(iRow,zeroIdx) > median(array(iRow,zeroIdx));
out(iRow,~zeroIdx) = array(iRow,~zeroIdx) > median(array(iRow,~zeroIdx));
end
答案 1 :(得分:3)
我提供简短的bsxfun
解决方案:
%// number of divisions
n = 4;
%// unshuffled matrix like in your example
unshuffled = bsxfun(@(a,b) mod(a,2*b) > b-1, meshgrid(1:n^2,1:n) - 1, (2.^((n-1):-1:0)).') %'
%// shuffle columns
shuffled = unshuffled(:,randperm(n^2))
unshuffled =
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
shuffled =
1 0 1 1 0 1 0 1 1 1 1 0 0 0 0 0
1 1 1 0 0 1 1 0 1 0 0 0 1 0 1 0
1 0 0 1 0 0 0 0 1 1 0 1 1 0 1 1
1 1 1 1 0 0 0 0 0 0 1 0 0 1 1 1
首先,您需要创建非抽动矩阵,这可以通过将meshgrid(1:n^2,1:n)
生成的矩阵与行相关模数进行比较来完成。最后你只需要洗牌。
答案 2 :(得分:3)
如果您拥有统计工具箱,则可以使用randsample
M = 3; %// number of rows
N = 16; %// number of columns. Should be multiple of 4, according to problem definition
result = zeros(M,N); %// preallocate and initiallize to zeros
result(1, randsample(1:N,N/2)) = 1; %// first row: half values set to one, half to zero
for m = 2:M
result(m, :) = result(m-1, :); %// initiallize row m equal to row m-1
result(m, randsample(find(result(m-1,:)), N/4)) = 0; %// change half of ones
result(m, randsample(find(~result(m-1,:)), N/4)) = 1; %// change half of zeros
end
示例结果:
result =
0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1
1 1 0 0 0 1 1 1 0 1 0 1 0 0 0 1
1 0 0 0 1 0 0 1 0 1 1 0 1 1 0 1
答案 3 :(得分:2)
使用Array
(
[0] => int ping(string $session_id)
[1] => string logout(string $session_id)
[2] => string login(string $user, string $password)
)
Fatal error: Call to undefined function login() in C:\.... on line 14
的解决方案:
randperm