how can i simplify this for loop?

2 views (last 30 days)
PJM
PJM on 8 Aug 2013
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?

Accepted Answer

kjetil87
kjetil87 on 8 Aug 2013
Edited: kjetil87 on 8 Aug 2013
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 Comments
kjetil87
kjetil87 on 8 Aug 2013
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 on 8 Aug 2013
Thank you for your help!! :D

Sign in to comment.

More Answers (1)

Evan
Evan on 8 Aug 2013
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)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!