How to generate a random matrix with conditions?

3 次查看(过去 30 天)
How to generate a matrix ( n x m ) where i need this number represent a number of ones in each row like this
A = [ 2 3 1
3 1 1
4 1 0
2 2 0 ]
I need to generate a matrix like this
X = [ 1 1 0 1 1 1 0 1
1 1 1 0 1 0 0 1
1 1 1 1 0 0 1 0
0 1 1 0 0 0 1 1 ]
Where every numbers in matrix A must be at least zero between its numbers of one
  1 个评论
Steven Lord
Steven Lord 2016-4-8
It sounds like the poster wants something like run-length decoding but where only the length of the runs of 1's are given and it's assumed there are 0's between those runs. But you're right, the poster needs to clarify the rules for how many 0's should be between the runs. It's not just one 0 between each run, as seen in rows 2, 3, and 4.

请先登录,再进行评论。

回答(3 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-4-8
编辑:Azzi Abdelmalek 2016-4-8
It's almost what you are asking for!
A = [ 2 3 1
3 1 1
4 1 0
2 2 0 ]
[n,m]=size(A);
ii=max(sum(A,2));
no=ii+m-1;
out=zeros(n,no);
for k=1:n
r=A(k,:);
nz=no-sum(r);
q=num2cell(zeros(1,m-1));
idx=randi(m-1,1,nz-m+1);
for kk=1:numel(idx)
q{idx(kk)}(end+1)=0;
end
aa=[];
for pp=1:m-1
aa=[aa ones(1,r(pp)) q{pp}];
end
aa=[aa ones(1,r(end))];
out(k,:)=aa;
end
out

Andrei Bobrov
Andrei Bobrov 2016-4-8
[m,n] = size(A);
X = zeros(m,sum(A,2) + n - 1);
a = arrayfun(@(x)ones(1,x),A,'un',0);
Xc(:,1:2:2*n-1) = a ;
Xc(:,2:2:end) = {0};
for ii = 1:m
b = [Xc{ii,:}];
X(ii,1:numel(b)) = b;
end

Azzi Abdelmalek
Azzi Abdelmalek 2016-4-8
编辑:Azzi Abdelmalek 2016-4-8
I think this is What you want:
A = [ 2 3 1
3 1 1
4 1 0
2 2 0 ]
[n,m]=size(A);
ii=max(sum(A,2));
no=ii+m-1;
out=zeros(n,no);
for k=1:n
r=A(k,:);
nz=no-sum(r);
q=[ cell(1) num2cell(zeros(1,m-1)) cell(1)];
idx=randi(m+1,1,nz-m+1);
for kk=1:numel(idx)
q{idx(kk)}(end+1)=0;
end
aa=q{1};
for pp=1:m
aa=[aa ones(1,r(pp)) q{pp+1}];
end
out(k,:)=aa;
end
out
  11 个评论

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by