How to instead the "for" loop?
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Richard Brown
2012-4-24
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!