Clear Filters
Clear Filters

I need to replace all the negative values with a reacuring loop of random values.

4 views (last 30 days)
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

Accepted Answer

Konstantinos Sofos
Konstantinos Sofos on 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

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!