Update a for loop with if statements
    10 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    gamer
 el 14 de Jun. de 2021
  
    
    
    
    
    Respondida: Joseph Cheng
      
 el 14 de Jun. de 2021
            Hello community,
thanks for trying to help me! I would be so happy if this will work.
First of all I created n spheres in a 15 x 7.5 field. They should move with the speed of v, which is always reduced by 0.001
Now thr question: How is it possible to change the direction (  make the element of v negative) when the spheres hit the borders. I tried it like this but it just changes the direction for only "one moment"
a = 15;
b = 7.5;
p=[r + (a-2*r)*rand(n,1),r + (b-2*r)*rand(n,1)];
v = rand(n,2);
for f = 1:1000 
    temp = v - 0.001 ; 
    temp(temp < 0.001) = 0 ; 
    v = temp;
    if ~any(v(:)) 
       break
    end
    p = p+v;
    for i = 1:n
 % check if ball hit borders
    if (p(i,1)<=r)      
        p(i,1)=r;        v(i,1) = -v(i,1);    % new direction of speed
    end                                         % unfortunately only for one moment
    if (p(i,1)>=(a-r))   
        p(i,1)=(a-r);    v(i,1) = -v(i,1); 
    end   
    if (p(i,2)<=r)    
        p(i,2)=r;        v(i,2) = -v(i,2);
    end
    if (p(i,2)>=(b-r))    
        p(i,2)=(b-r);    v(i,2) = -v(i,2);
    end
    end
end
0 comentarios
Respuesta aceptada
  Joseph Cheng
      
 el 14 de Jun. de 2021
        Without running your code i think you can create a sign variable of (-1)^(0 or 1) which switches between 0 or 1 depending on when it hits.  then you keep using that value.  This will also give you a variable that changes sign for either adding or subtracting the velocity slow down.
0 comentarios
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

