I need to change n elements in an array chosen randomly

1 view (last 30 days)
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 Comments
Steven Lord
Steven Lord on 10 Nov 2021
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 on 10 Nov 2021
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.

Sign in to comment.

Answers (1)

dpb
dpb on 10 Nov 2021
Edited: dpb on 11 Nov 2021
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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!