How to check condition element by element till satisfied
    6 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Offroad Jeep
 el 8 de Mayo de 2016
  
    
    
    
    
    Respondida: Elias Gule
      
 el 9 de Mayo de 2016
            if true
  clc
clear all
format compact
a = ones(5)
w_rand = rand()
if w_rand > 0.5
a = -1
end
I want to generate random numbers for each element. now in the first condition the elements which get w_rand > 0 should flip to -1 and its value is fixed. now again the w_rand should be generated for the remaining 1 which satisfy the condition of w_rand should flip to -1. and the process goes on till the time all 1 goes to -1. in my code the all values change to -1 at once. where as i want to do this element by element
1 comentario
  Image Analyst
      
      
 el 8 de Mayo de 2016
				"a" is a 5-by-5 array of random numbers. In your "first condition" you get an random number and check if it's greater than 0.5 and then "the elements" get set to -1.  WHICH elements should get flipped? All of them? Some of them? Is so, which ones? All you're doing is changing "a" from a 5-by-5 array to a single scalar number. Anyway, you're going to need a while loop and the all() function to check that every element in "a" got set to -1.
Respuesta aceptada
  Elias Gule
      
 el 9 de Mayo de 2016
        I hope this is what you're looking for:
a   = ones(5);
sz = size(a);
a  = a(:);
count = 0;
isDebug = true; %%So you know the while loop is running
for kk = 1 : length(a)
  akk = a(kk);
  while rand() < 0.5
      if isDebug
          fprintf('a(%d) = %d;\n',kk,akk);
      end
  end
  a(kk) = -1;
end
a = reshape(a,sz);
0 comentarios
Más respuestas (0)
Ver también
Categorías
				Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


