答案 0 :(得分:1)
这将获得每列中放置1的数量,因为它只有1,我们被认为在转置后,新矩阵每行只有一个1。
参数是生成的矩阵中的行数和列数。
function [M] = getMat(n,d)
M = zeros(d,n);
sz = size(M);
nnzs = 1;
inds = [];
for i=1:n
ind = randperm(d,nnzs);
inds = [inds ind.'];
end
points = (1:n);
nnzInds = [];
for i=1:nnzs
nnzInd = sub2ind(sz, inds(i,:), points);
nnzInds = [nnzInds ; nnzInd];
end
M(nnzInds) = 1;
M = M.';
end
示例:
getMat(5, 3)
ans =
0 0 1
1 0 0
0 1 0
1 0 0
0 0 1
答案 1 :(得分:1)
我建议采用以下方法:
N = 3; M = 6; %defines input size
mat = zeros(M,N); %generates empty matrix of NxN
randCols = randi([1,N],[M,1]); %choose columns randomally
mat(sub2ind([M,N],[1:M]',randCols)) = 1; %update matrix
结果
mat =
0 0 1
1 0 0
0 0 1
0 0 1
0 1 0
0 1 0
答案 2 :(得分:0)
考虑这种方法:
% generate a random integer matrix of size m by n
m = randi(5,[5 3]);
% find the indices with the maximum number in a row
[Y,I] = max(m, [], 2);
% create a zero matrix of size m by n
B = zeros(size(m));
% get the max indices per row and assign 1
B(sub2ind(size(m), 1:length(I), I')) = 1;
结果:
B =
0 1 0
0 0 1
1 0 0
0 1 0
1 0 0