フィルターのクリア

how can i simplify this for loop?

1 回表示 (過去 30 日間)
PJM
PJM 2013 年 8 月 8 日
for i=1:2 %for-loop1
for j=1:5 %for-loop2
x(j)=i;
y(j)=j+1;
t=[x; y]';
end
for j=1:5 %for-loop3
t(j,1)=t(j,1)+j;
t(j,2)=t(j,2)+2*j;
end
if i==1 %if
a=t;
elseif i>1
a=[a; t];
end
end
disp(a);
thanks for your advice and help.
---------------------------
OHHHH.. I'm sorry for my stupid question.
upper code is simplification, and
for i=1:10 %for-loop1
for j=1:11 %for-loop2
ca=Gimg(round((i-8/10)*H):round((i-2/10)*H),round((j-8/10)*W):round((j-2/10)*W));
if mean(mean(ca))<60
ca(ca>mean(mean(ca))-3)=0;
else
ca(ca<mean(mean(ca))+3)=0;
end
[x(j) y(j)]=pjm_centroid(ca);
array=[x; y]';
end
for j=1:11 %for-loop3
array(j,1)=array(j,1)+round((j-8/10)*W);
array(j,2)=array(j,2)+round((i-8/10)*H);
end
if i==1 %if
p=array;
elseif i>1
p=[p; array];
end
end
disp(p);
---------------------
this is an originally code.
variables i and j are meaningful I think.
When you compare simplification and of original code,
how can I simplify structure of for-loop in original code?

採用された回答

kjetil87
kjetil87 2013 年 8 月 8 日
編集済み: kjetil87 2013 年 8 月 8 日
a=[];
t=zeros(5,2);
for i=1:2
t(:,1)=(1:5)+i;
t(:,2)=(2:6)+2*(1:5);
a=[a;t];
end
disp(a)
You can also get rid of the for i=1:2 but i included it to show the process.
a=zeros(10,2);
a(:,1)=[(2:6),(3:7)];
a(:,2)=repmat((2:6)+2*(1:5),1,2); %or just hardcode
%t(:,2)=[(2:6)+2*(1:5),(2:6)+2*(1:5)]
disp(a)
  3 件のコメント
kjetil87
kjetil87 2013 年 8 月 8 日
Also from a closer look at your code you may have intended to move
array=[x,y]';
below the end line of for loop 2. Now you are doing 10 meaningless operations before you overwrite it again with the correct result of x and y.
PJM
PJM 2013 年 8 月 8 日
Thank you for your help!! :D

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

その他の回答 (1 件)

Evan
Evan 2013 年 8 月 8 日
Here's how you can get rid of the nested loops:
a = [];
for i = 1:2
x(1:5) = i;
y(1:5) = (1:5) + 1;
t = [x; y]';
t(1:5,1) = t(1:5,1) + (1:5)';
t(1:5,2) = t(1:5,2) + 2*(1:5)';
a = [a; t];
end
disp(a)

カテゴリ

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