Sparse Matrix with Same number of non-zero values in each column
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Maxine Killingsworth
le 9 Oct 2021
Commenté : Maxine Killingsworth
le 9 Oct 2021
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
----------------------
Réponse acceptée
Chunru
le 9 Oct 2021
A = createMatrix(8, 4);
full(A)
function A = createMatrix(n, k)
A = sparse(n,n);
for i=1:n
A(randperm(n, k), i) = 1/k;
end
end
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Sparse Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!