# How to replace a for loop with a nested if-else condition, to get more velocity

5 visualizaciones (últimos 30 días)
Ana Gonçalves el 3 de Jun. de 2022
Respondida: Pooja Kumari el 27 de Jun. de 2022
I have a huge vector, and time does matter to my application. I'd like to know how to gain velocity in a code simillar to the shown below (but of course, it is much more complex than this example) :
z = randi(3000);
tic
for i = 1:length(z)
if z(i) <= 15
z(i) = [];
% do something else ...
end
end
toc
Elapsed time is 0.002744 seconds.
##### 1 comentarioMostrar NingunoOcultar Ninguno
Rik el 3 de Jun. de 2022
z(z<=15)=[]; will do the same as your loop. How to vectorize code depends strongly on the details of what you want to do.

Iniciar sesión para comentar.

Pooja Kumari el 27 de Jun. de 2022
Dear Ana,
I am Pooja Kumari and it is my understanding that you want to replace a for loop with nested if-else condition to improve velocity.
%for the provided code
z = randi(3000);
tic
for i = 1: length(z)
if z(i) <= 15
z(i) = [];
% Do something else ...
end
end
toc
You can replace the for loop and if condition given in this code by the following code:
z = randi(3000);
tic
z(z<=15) = []; %updated code
toc
Sincerely,
Pooja Kumari
##### 0 comentariosMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos

Iniciar sesión para comentar.

### 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!