Sparse Matrix with Same number of non-zero values in each column

2 ビュー (過去 30 日間)
Maxine Killingsworth
Maxine Killingsworth 2021 年 10 月 9 日
I want to modify the following function. Right now the function takes n (size of matrix) and outputs a sparse matrix with numbers at random lcations, where each column adds up to 1.
I want the function to: take in n and k, where n is the size of matrix, and k is the number of non-zero elements in each column. Each column still needs to add up to 1. So each non-zero value will be 1/k, and each column will have k non-zero elements. The number of non-zero elements is the same, but the location is randomized. I have attached a photo example of what I want.
----------------------
function A = createMatrix(n)
A = sparse(n,n);
maxnel = min(16,n);
for i = 1:n
nel = floor(rand(1)*maxnel);
if(nel == 0)
val = 0;
else
val = 1/nel;
end
for j = 1:nel
col_ind = ceil(rand(1)*n);
while(A(col_ind,i) ~= 0)
col_ind = ceil(rand(1)*n);
end
A(col_ind,i) = val;
end
end
----------------------

採用された回答

Chunru
Chunru 2021 年 10 月 9 日
A = createMatrix(8, 4);
full(A)
ans = 8×8
0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0 0.2500 0.2500 0.2500 0 0.2500 0 0 0.2500 0 0 0.2500 0.2500 0 0 0.2500 0 0 0.2500 0 0 0 0 0 0.2500 0 0 0.2500 0 0.2500 0.2500 0 0.2500 0.2500 0 0 0.2500 0.2500 0.2500 0.2500 0 0.2500 0 0 0 0 0 0.2500 0 0 0.2500 0 0.2500 0 0.2500 0
function A = createMatrix(n, k)
A = sparse(n,n);
for i=1:n
A(randperm(n, k), i) = 1/k;
end
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by