I need to replace all the negative values with a reacuring loop of random values.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Walshaikhli
le 10 Mar 2015
Commenté : Walshaikhli
le 10 Mar 2015
SO I need to have a vector of random values (between -10 and 10) then replace the negative integers with another random number (using a while loop I assume) until all the numbers are positive. After all that is done I need to count the number of times it took before all the numbers became positive ( I will probably use count to do this) This is a suggested homework question that I have been stuck on for 2 weeks and I can tell that something similar is going to be on the exam next week.
Here is what I have so far.
a=-10; % min value
b=10; % max value
v = randi([-10,10],1,20) % generates Vector with 20 random integers
R = randi([-10,10],1,20) % Another random array to replace values
for n=1:10 % How can I use a while loop in this case?
idx = v < 0 % Am I doing the indexing right?
v(idx) = R(idx)
%finally How can I make the count?
end
0 commentaires
Réponse acceptée
Konstantinos Sofos
le 10 Mar 2015
Hi,
There many and different solutions on your problem
r1 = randi([-10,10],1,20); % first sample
idx = find(r1<0); % indexation of negatives
counter = 0; % initialize a counter
while any(idx)~=0
r2 = randi([-10,10],1,20);
r1(idx)=r2(idx);
idx = find(r1<0);
counter = counter + 1;
end
fprintf('Counter = %d\n',counter)
Regards
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!