How do I generate multiple binary matrices containing a single one in each row?

I want to generate multiple m x n (size of known matrix A) binary matrices. The rule to respect is that every row has to contain a single 1.
Suppose I want to generate 10 matrices called randmat of size(A). This is the code I've written combining suggestions found on this forum. It should use a for cycle to generate random matrices of 0 and 1, then force each row to sum up to 1. The problem is that I'm using variables of different type, and the code doesn't work (MATLAB error: 'Unable to perform assignment because brace indexing is not supported for variables of this type').
for i = 0:9
[r,c] = size(A);
randmat{i+1} = randi([0 1],r,c);
rowsum = sum(randmat,2);
randmat{i+1} = bsxfun(@rdivide,randmat{i+1},rowsum);
end
How could It be solved?
Thanks in advance for your help.

댓글 수: 3

For any one matrix
sparse(1:r, randi(c, q, r))
Thank you for your comment. Sparse can help saving some memory. However, as you've written it, the syntax means that 1:r stands for the number of rows, and randi(c, q, r) is the number of columns. This gives the sparse error 'Sparse matrix sizes must be non-negative integers less than MAXSIZE as defined by COMPUTER'. Am I mistaken?
By writing:
A=sparse(randi([0 1],r,c))
I get a sparse matrix of size rxc made of zeros and ones, which still doesn't answer my original question.
Sorry, typo, on my phone 1 is long-press q so should have been randi(c, 1, r)

댓글을 달려면 로그인하십시오.

 채택된 답변

Davide Biaggini
Davide Biaggini 2019년 7월 31일
편집: Davide Biaggini 2019년 7월 31일
For those interested, here is the working solution that I found. The code generates a sequence of values via rand and sets the maximum of each row to 1, while the other values are set to 0. Each random binary array is stored in the initial 3d matrix. As example, in order to generate 5 random 7x3 binary matrices, containing only a single 1 in each row:
k=5; % number of (mxn) matrices
m=7;
n=3;
M = rand(m,n,k);
for i=1:k
M(:,:,i) = double(bsxfun(@eq, M(:,:,i), max(M(:,:,i), [], 2)));
end

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2019년 7월 31일
편집: Andrei Bobrov 2019년 8월 1일
May be so?
m = 8;
n = 6; % [m,n] = size(A);
k = 10;
[~,Anew] = sort(rand(m,n,k),2);% here fixed
M = Anew == 1;

댓글 수: 3

Thank you for your answer. I tried your code, and I like the idea of employing the cell type and a 3d dimension to allocate the results, but It's generating a cell that contains matrices just made of zeros. I also don't understand the purpose of your use of the function sort. Could you please expand on that? Thank you again for your help.
Thank you again! That's an elegant solution!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by