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

2 次查看（过去 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 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

### Community Treasure Hunt

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

Start Hunting!