How to generate a random matrix with conditions?
3 views (last 30 days)
Show older comments
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 Comment
Steven Lord
on 8 Apr 2016
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.
Answers (3)
Azzi Abdelmalek
on 8 Apr 2016
Edited: Azzi Abdelmalek
on 8 Apr 2016
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
0 Comments
Andrei Bobrov
on 8 Apr 2016
[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
0 Comments
Azzi Abdelmalek
on 8 Apr 2016
Edited: Azzi Abdelmalek
on 8 Apr 2016
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 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!