I need to change n elements in an array chosen randomly
조회 수: 2 (최근 30일)
이전 댓글 표시
How do I change n elements in an array but chosen randomly? The code below favors the first matrix elements evaluated which I don't want. I only want to set the matrix value to 1 only n - 1 times.
for i = 1:n
%Starting from i only changes upper matrix triangle
for j = i:n
if i == j
A(i,j) = 1;
else
r = randi(100);
if r < 50
if num_connected < n-1
num_connected = num_connected + 1;
A(i,j) = 1;
end
end
end
end
end
댓글 수: 2
Steven Lord
2021년 11월 10일
How do I change n elements in an array but chosen randomly?
How specifically do you want to choose? Do you want to select exactly n different elements to change? Or do you want each element to have an n/numel chance of being chosen, which may not give you exactly n changed elements?
답변 (1개)
dpb
2021년 11월 10일
편집: dpb
2021년 11월 11일
Not totally clear yet just what are valid locations to be changed -- the above code sets the diagonal elements to one anyways; if one wants N other random locations to be set to one, then something like
N=YourMagicNumber;
I=randperm(numel(M),N); % select N random locations from the total indices available
[r,c]=ind2sub(size(A),I); % check don't have diagonal element
if any(r==c)
% regenerate any for which r,c are same here if that's important
end
A(I)=1;
Alternatively, to select only off diagonal elements a priori...
A=eye(M); % the starting array of size MxM
I=setdiff(1:numel(A),find(A)); % non-diagonal indices into A
N=YourMagicNumber;
I=I(randperm(numel(I),N)); % select N random locations from collection
A(I)=1;
No regeneration would be needed this way, the indices are exclusive of the diagonal elements.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!