how can i simplify this for loop?

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by