Change of sign in a matrix one by one

1 回表示 (過去 30 日間)
Offroad Jeep
Offroad Jeep 2016 年 11 月 28 日
コメント済み: KSSV 2016 年 11 月 28 日
Hi to all the users. I have a matrix A = ones(5), I want to change the sign of elements one by one but under the condition with rand(1).
Pick random position 1 in A then take rand_number = rand(1) if rand_number>=0.5 fix that 1 to -1
else 1 remains 1 then again pick 1 from the remaining 1s in the matrix A continue till all ones go to -1
Hope i have explained well.
Regards

回答 (1 件)

KSSV
KSSV 2016 年 11 月 28 日
編集済み: KSSV 2016 年 11 月 28 日
A = ones(5) ;
Ac = A(:) ;
pos = 1:length(Ac) ;
for i = 1:length(pos)
rand_pos = randsample(pos,1) ;
if rand(1) > 0.5
Ac(rand_pos) = -1 ;
end
pos = setdiff(pos,rand_pos) ;
end
A = reshape(Ac,5,5) ;
  3 件のコメント
KSSV
KSSV 2016 年 11 月 28 日
Your condition was if rand(1) > 0.5 then change 1 to -1.
KSSV
KSSV 2016 年 11 月 28 日
A = ones(5) ;
Ac = A(:) ;
pos = 1:length(Ac) ;
while ~isempty(pos)
rand_pos = randsample(pos,1) ;
if rand(1) > 0.5
Ac(rand_pos) = -1 ;
pos = setdiff(pos,rand_pos) ;
end
end
A = reshape(Ac,5,5) ;

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

カテゴリ

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