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
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
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
0 件のコメント
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
0 件のコメント
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 Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!