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

1 次查看(过去 30 天)
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

采纳的回答

Konstantinos Sofos
Konstantinos Sofos 2015-3-10
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by