필터 지우기
필터 지우기

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 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