Borrar filtros
Borrar filtros

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

4 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Konstantinos Sofos
Konstantinos Sofos el 10 de Mzo. de 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

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by