我正在尝试构建一个稀疏矩阵,每行和每列至少包含一个随机数。
在这个例子中,我形成了4x4随机矩阵,稀疏度为0.5。 然后我尝试遍历行,检查是否只有零,并将随机数添加到该行,如果它们是随机位置。但这不起作用,所以我很感激帮助。
A = sprand (4,4,0.5);
A = full (A);
[n m] = size(A);
x=1;
for i = 1:n
if any(A,2) == 0
j= randperm(m,x);
A(i,j) = rand;
end
end
答案 0 :(得分:1)
基本上,对于矩阵mxm,你想要n< m * m分散在矩阵中的随机数,每行和每列至少有一个数字。这个解决方案怎么样:
2017-08-10
我明白了:
SUBSTR(column3, 1,10)
答案 1 :(得分:1)
sz=4;
A=zeros(sz);
%Generating one random number in every row and column
A(sub2ind([sz sz],randperm(sz),1:sz))=randn(sz,1);
%The following either generates no indices satisfying the *at least* condition or
%generates some indices since there can be more than one RN in every row and column
ind = randi([1 sz*sz],1, randi([0 sz*sz],1,1));
A(ind)=randn(1,length(ind)); %More random numbers on the generated indices