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