How to instead the "for" loop?

1 回表示 (過去 30 日間)
Peony Lai
Peony Lai 2012 年 4 月 24 日
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

回答 (1 件)

Richard Brown
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
  3 件のコメント
Peony Lai
Peony Lai 2012 年 4 月 24 日
Thankyou.
I had try this but the time is also the same. Didn't decrease, any other method? Thanks
Peony Lai
Peony Lai 2012 年 4 月 24 日
Dear Walter Roberson,
Thankyou, I try this but have a error,
"??? Subscripted assignment dimension mismatch."
so that the program cannot run

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by