How to replace all elements that are not even integers?

need to generate an array with 20 random integers, and replace all that are not even with another random integer
v=randi([10 30],1,20)
v1 = 0;
N = -1;
while N<0
N = 1;
for k = 1:20
if(~rem(v(k),2))
v1(k) = v(k);
end
end
end

2 件のコメント

James Tursa
James Tursa 2018 年 3 月 30 日
編集済み: James Tursa 2018 年 3 月 30 日
Where is your "replacing" code? I don't see any code under your "not even" test that generates another replacement random integer. Also, you should double check your "not even" test to make sure it is doing what you think it is doing. How is the N variable connected to your algorithm? I don't see any connection.
edward wiltz
edward wiltz 2018 年 3 月 30 日
編集済み: edward wiltz 2018 年 3 月 30 日
This is how far I got, would you point me in the right direction. How can I replace elements that are not divisible by 2, with another random number until it is divisible by 2

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

 採用された回答

Birdman
Birdman 2018 年 3 月 30 日

0 投票

This should help:
N=20;idx=1:N;
while true
v(idx)=randi([10 30],1,N);
if all(mod(v,2)==0)
break;
else
idx=find(mod(v,2)~=0);
N=numel(idx);
v(idx)=0;
end
end

その他の回答 (1 件)

David Fletcher
David Fletcher 2018 年 3 月 30 日

0 投票

A different way of doing it - generate a list of random integers much larger than the number you need, and pick out the subset of even numbers. Generate another list of random indices and use that to pick out 20 even numbers from the subset of even 'random' numbers (or just pick out the first 20 - I'm not sure it would make much difference)
list=randi([1 100],1,1000)
evenIndices=mod(list,2)==0
evenNums=list(evenIndices)
indexer=randperm(length(evenNums))
evenNums=evenNums(indexer(1:20))
NB - I make no claim concerning the validity of the 'randomness' of this method

カテゴリ

ヘルプ センター および File ExchangeRandom Number Generation についてさらに検索

質問済み:

2018 年 3 月 30 日

回答済み:

2018 年 3 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by