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

조회 수: 3 (최근 30일)
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 CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by