How to instead the "for" loop?

2 visualizaciones (últimos 30 días)
Peony Lai
Peony Lai el 24 de Abr. de 2012
Hello, I had a program which use for loop and if, but it take a long time, I want it faster.
How Can I instead of "for" and "if" so that it can make the program become faster?
Here is the program, Thanks
tic
clear all
close all
mov = mmreader('02.avi');
for i = 1: 7111 % number of the frame of the video
frame1 = read(mov, i);
if i == 750
for a = 300 :2: 303;
for b = 353 :2: 381;
for c = 301 :2: 303;
for d = 354 :2: 381;
frame1(a,b,:) = [0,0,0];
frame1(c,d,:) = [0,0,0];
end
end
end
end
for a = 300 :2: 303;
for b = 354 :2: 381;
for c = 301 :2: 303;
for d = 353 :2: 381;
frame1(a,b,:) = [153,153,153];
frame1(c,d,:) = [153,153,153];
end
end
end
end
end
if i == 760
for a = 300 :2: 303;
for b = 356 :2: 385;
for c = 301 :2: 303;
for d = 357 :2: 385;
frame1(a,b,:) = [153,153,153];
frame1(c,d,:) = [153,153,153];
end
end
end
end
for a = 300 :2: 303;
for b = 357 :2: 385;
for c = 301 :2: 303;
for d = 356 :2: 385;
frame1(a,b,:) = [0,0,0];
frame1(c,d,:) = [0,0,0];
end
end
end
end
end
for x = 1 : 478;
for y = 1 : 640;
if frame1(x,y,1) == frame1(x,y,2) && frame1(x,y,2) == frame1(x,y,3) && frame1(x+1,y,1) == frame1(x+1,y,2) && frame1(x+1,y,2) == frame1(x+1,y,3) && frame1(x+2,y,1) == frame1(x+2,y,2) && frame1(x+2,y,2) == frame1(x+2,y,3)
figure; imagesc(frame1);
title(['Frame ', num2str(i)])
xlabel('x-axis');
ylabel('y-axis');
coordinate = [x y]
frame1 = read(mov, i+1);
end
end
end
end
toc
Thanks

Respuestas (1)

Richard Brown
Richard Brown el 24 de Abr. de 2012
Un-nest your loops - your a,b and c,d loops are independent of each other. What you're doing is running your inner two loops gazillions of times more than you need to. I.e. replace your four-level loops with these:
for a = ...
for b = ...
frame1(a, b, :) =...
end
end
for c = ...
for d = ...
frame1(c, d, :) =...
end
end
  3 comentarios
Peony Lai
Peony Lai el 24 de Abr. de 2012
Thankyou.
I had try this but the time is also the same. Didn't decrease, any other method? Thanks
Peony Lai
Peony Lai el 24 de Abr. de 2012
Dear Walter Roberson,
Thankyou, I try this but have a error,
"??? Subscripted assignment dimension mismatch."
so that the program cannot run

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by