gpt4 book ai didi

matlab - 如何用零随机替换非零元素?

转载 作者:行者123 更新时间:2023-12-01 12:27:10 26 4
gpt4 key购买 nike

我有一个包含10元素的矩阵,如下所示,它用作网络邻接矩阵。

A =

0 1 1 1
1 1 0 1
1 1 0 1
1 1 1 0

我想模拟对网络的攻击,因此我必须用 1随机替换某些特定百分比的 0元素。如何在MATLAB中执行此操作?

我知道如何用零随机替换一定百分比的元素,但是我必须确保随机替换的元素是矩阵而不是零的 1元素之一。

最佳答案

如果要以一定的概率更改每个1:

p = 0.1%; % desired probability of change

A_ones = find(A); % linear index of ones in A
A_ones_change = A_ones(rand(size(A_ones))<=p); % entries to be changed
A(A_ones_change) = 0; % apply changes in those entries

如果要随机更改 1条目的固定部分:
f = 0.1; % desired fraction

A_ones = find(A);
n = round(f*length(A_ones));
A_ones_change = randsample(A_ones,n);
A(A_ones_change) = 0;

请注意,在这种情况下,由于需要舍入到整数个条目,因此所得分数可能与预期的分数不同。

关于matlab - 如何用零随机替换非零元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18277978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com