2017-08-21 8 views
1

すべての行と列に少なくとも1つの乱数を含む疎行列を作成しようとしています。すべての行と列に少なくとも1つの数値を持つ行列

この例では、希薄度0.5の4x4ランダムマトリックスを形成します。 次に、行を調べ、ゼロだけがあるかどうかを確認し、その行に乱数をランダムな位置に追加します。しかし、これはうまくいかないので、私は助けていただければ幸いです。

A = sprand (4,4,0.5); 
A = full (A); 
[n m] = size(A); 
x=1; 
for i = 1:n 
if any(A,2) == 0 
j= randperm(m,x); 
A(i,j) = rand; 
end 
end 
+1

あなたはこの行は何だと思いますか? 'A(1、randperm(1));'? コードを確認してください。 – crazyGamer

+0

あなたのコメントをありがとう、私は今編集しましたが、それでも動作しません。私の考えは、すべて0の行のランダムな位置に乱数を加えることです。 –

答えて

1
sz=4; 
A=zeros(sz); 
%Generating one random number in every row and column 
A(sub2ind([sz sz],randperm(sz),1:sz))=randn(sz,1); 

%The following either generates no indices satisfying the *at least* condition or 
%generates some indices since there can be more than one RN in every row and column 
ind = randi([1 sz*sz],1, randi([0 sz*sz],1,1)); 
A(ind)=randn(1,length(ind)); %More random numbers on the generated indices 
+0

あなた、それは素晴らしい作品です! –

1

基本的には、行列のためにあなたはすべての行と列の内の少なくとも1つの番号で、マトリックス状に点在n個<メートル×m個の乱数をしたいMXM。どのようにこのソリューションについて:

% Matrix size 
m = 4; 
% Unique random rows and columns 
rows = [randperm(m) , randi(m,1,randi(m*m))]; 
columns = [randperm(m) , randi(m,1,numel(rows)-4)]; 

% Convert subscripts to linear indices 
idx = unique(sub2ind([m , m] , rows , columns)); 

% Generate m random numbers 
numbers = randn(numel(idx),1); 

% Fill in the sparse matrix 
A = zeros(m); 
A(idx) = numbers 

私が手:

A = 

0.5139   0 0.1652   0 
    0   0 -0.7116 0.4037 
    0   0 1.6185 -0.3431 
    0 -0.6699 0.6193   0 
+0

これは、OPが各行とカラムで少なくとも* 1つの乱数を求めている間に、常に各行と列に1つの乱数を生成します。 –

+0

@Sardar Usamaは詳細を指摘してくれてありがとうございます。 「少なくとも」ビット。 – Zep

+0

@Sardar Usamaはい、 'unique 'ビットは' randi'によって生成されたインデックスを削除するかもしれないからです。私は1000シリーズのインデックスを生成してブルートフォースでそれをテストし、それらのうちのいくつかは長さm(すなわち、行/列ごとに1つの要素)を持っています – Zep

関連する問題