在矩阵的每一行只生成一个非零元素

时间:2017-08-01 06:32:11

标签: matlab

我想构建一个矩阵,其中我们不仅有一个" 1 "在每一行,但也在随机位置。 e.g。

enter image description here

我希望矩阵的大小为m by n。任务似乎很简单,但我不确定这样做的方法是什么。谢谢。

3 个答案:

答案 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

参考:GApplication.send_notification

相关问题