# Sparse matrix with diagonal zero and elements in every row/column

8 ビュー (過去 30 日間)
Evelyn Salt 2017 年 8 月 18 日
コメント済み: Evelyn Salt 2017 年 8 月 22 日
I'm trying to produce a sparse matrix that has zeros on the diagonal, but also has at least one element in each row and column.
With this code I get the first part, but I don't know how to make sure that each row and column have elements in them.
R = sprand(4,4,0.5);
r = 0 + (0.5 - 0)*rand(4,4);
A = full (R);
A(1:4+1:4*4)=0;
Nonz = nnz(A);
Diff = ceil(0.5*(4^2-4)) - Nonz;
B = find (A==0);
A=A';
B = find (A==0);
C = setdiff(B,1:4+1:4*4);
D = datasample(C,Diff,1,'Replace',false);
E=A;
for i = 1:length(D)
E(D(i)) = 1;
end
E=E';
E(find(E)) = r(find(E));
##### 2 件のコメント表示 1 件の古いコメント非表示 1 件の古いコメント
Evelyn Salt 2017 年 8 月 18 日
Sorry, you are right, I messed something up. Now I edited my code and you can see that I get the matrix E which doesn't necessarily have elements in every row and column.

サインインしてコメントする。

### 採用された回答

Chris Perkins 2017 年 8 月 21 日
Hi Evelyn,
The code below shows how to compute a sparse square matrix where each row and column have at least one non-zero value, given a dimension size.
It computes a sparse matrix, and then tests for whether the matrix meets the row and column conditions, generating a new matrix until it does, so the final matrix avoids bias from removing elements.
% Specify size of matrix
dim = 4;
% Compute probability for sparse matrix based on size of matrix
density = 1 - (1 - 1/(2^(1/dim)))^(1/(dim-1));
% Create sparse matrix
A = full(sprand(dim,dim,density));
% Set diagonal to zeroes
A(eye(size(A)) ~= 0) = 0;
% Check that A satisfied conditions (no row or column with all zeroes)
% If A does not, re-compute A and check again
while ~(all(any(A,1)) && all(any(A,2)))
A = full(sprand(dim,dim,density));
A(eye(size(A)) ~= 0) = 0;
end
When I tested this, it found a valid matrix in a small number of iterations each time.
If you need the matrix to be either sparser or less sparse, you can adjust 'density' to either a different function or a constant to adjust the average number of elements in the matrix.
##### 1 件のコメント表示 なし非表示 なし
Evelyn Salt 2017 年 8 月 22 日
Smart! Thank you, this solves my problem!

サインインしてコメントする。

### カテゴリ

Find more on Operating on Diagonal 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!

Translated by