I need to change n elements in an array chosen randomly

조회 수: 2 (최근 30일)
Matthew Pickard
Matthew Pickard 2021년 11월 10일
편집: dpb 2021년 11월 11일
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
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?
Matthew Pickard
Matthew Pickard 2021년 11월 10일
I want to select n -1 elements to change. The code above selects the first n -1 found randomly. But this is not distributed across all the ones looked at. Background: I have 10 vertices and I want to make 9 random connections between them. This is related to a minimu spanning tree analysis. Thanks for your attention.

댓글을 달려면 로그인하십시오.

답변 (1개)

dpb
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.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by