nam
nam

Reputation: 215

Generate only one non-zero element at each row of a matrix

I would like to construct a matrix in which we not only have one "1" at each of the rows but also at a random position. e.g.

enter image description here

I want the size of the matrix is of size m by n. The task seems simple, but I am not sure what is the neat way to do this. Thank you.

Upvotes: 2

Views: 1402

Answers (3)

Ekaba Bisong
Ekaba Bisong

Reputation: 2982

Consider this approach:

% 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;

Result:

B =

    0     1     0
    0     0     1
    1     0     0
    0     1     0
    1     0     0

Reference: Matrix Indexing in MATLAB

Upvotes: 0

ibezito
ibezito

Reputation: 5822

I suggest the following approach:

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

Results

mat =

 0     0     1
 1     0     0
 0     0     1
 0     0     1
 0     1     0
 0     1     0

Upvotes: 1

Tony Tannous
Tony Tannous

Reputation: 14871

This will get the number of 1's to put in each column, since it is only 1, we are granted that after transpose, the new matrix will have only one 1's in each row.

Parameters are number of rows and columns in the generated matrix.

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

Example:

getMat(5, 3)

ans =

     0     0     1
     1     0     0
     0     1     0
     1     0     0
     0     0     1

Upvotes: 1

Related Questions