Adding or subtracting the same number

4 ビュー (過去 30 日間)
Yi Chuan Xie
Yi Chuan Xie 2020 年 10 月 31 日
回答済み: Vladimir Sovkov 2020 年 10 月 31 日
Hi, I have a array, for example, [0 0 0 0 ]
And I want each of them to be randomly adding 0.4 or subtracting 0.4
How do I do that?

回答 (1 件)

Vladimir Sovkov
Vladimir Sovkov 2020 年 10 月 31 日
n=4; % array length
x=zeros(1,n); % sample array
d=0.4; % value to be added/subtracted
k=rand(1,n); % uniformly random number between 0 and 1
x(k<0.5)=x(k<0.5)-d; % subtraction
x(k>=0.5)=x(k>=0.5)+d; % addition
many other ways are possible

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by