how to replace the element with random number based if statement

1 回表示 (過去 30 日間)
Genz
Genz 2019 年 10 月 16 日
コメント済み: sid Chen 2019 年 10 月 17 日
Helllo everyone
i have a problem to change element of array with iteration approach. refer to https://www.mathworks.com/matlabcentral/answers/8817-how-to-replace-the-elements-of-a-matrix-using-the-conditions-if-else , i have same problem but little different. for instance i have mut1 = [.11 .12 .13 .14 .15 .16 .17 .18 .19 .20] and constan number 0.5. i want to replace element of mut1 with 'random number between' if random number(rmi) < 0.5. so this is what iam doing.
mutC = zeros(size(mut1));
pm = 0.5;
for i = 1:numel(mut1)
rmi = rand(1,1)
rCm = rbC+(raC-rbC).*rand(1,1)
if rmi<pm
mutC = rCm
else
mutC = mut1
end
end
but the final result is always mutC = mut1. there is no number from rCm.
I will appreciate any help. thank you.

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 10 月 16 日
編集済み: Andrei Bobrov 2019 年 10 月 16 日
mutC = mut1;
[m,n] = size(mut1);
pm = 0.5;
rmi = rand(m,n);
rCm = rbC+(raC-rbC).*rand(m,n);
for i = 1:numel(mut1)
if rmi(i) < pm
mutC(i) = rCm(i);
end
end
or
pm = .5;
mutC = mut1;
[m,n] = size(mut1);
rCm = rbC+(raC-rbC).*rand(m,n);
lo = rand(m,n) < pm;
mutC(lo) = rCm(lo);
  3 件のコメント
Andrei Bobrov
Andrei Bobrov 2019 年 10 月 16 日
I'm fix.
Genz
Genz 2019 年 10 月 16 日
many thanks sir. 2 thumbs up..
GBU.

サインインしてコメントする。

その他の回答 (1 件)

sid Chen
sid Chen 2019 年 10 月 16 日
Andrei Answer is very clear.
The problem is
if rmi<pm
mutC = rCm
else
mutC = mut1
with these code, you replace the whole matrix, all the elements are replaced.
To avoid this, you need to replace only one elements step by step. Just add an subscipt 'i' to point the element to be repalced.
if rmi<pm
mutC(i) = rCm(i)
else
mutC(i) = mut1(i)
  2 件のコメント
Genz
Genz 2019 年 10 月 16 日
when i run this code become error "index exceeds matrix dimensions"
sid Chen
sid Chen 2019 年 10 月 17 日
if rmi<pm
mutC(i) = rCm % change here, rCm is a number,not a matrix
else
mutC(i) = mut1(i)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

製品


リリース

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by