# I want to reduce the repeated for loops as i explained below. any help??

1 view (last 30 days)
M.Prasanna kumar on 22 Aug 2019
Answered: Guillaume on 22 Aug 2019
when SS =1 , KK loop should not take the value from 1 to 3
when SS = 2:23 , KK loop should not run for SS-1:SS+1
when SS =24 , KK loop should not take the value from 22 to 24
I am able to get the answer but i dont want to repeat the same code for three times. how to resolve the problem???
for ss = 1
for ii = 1:no_gridsx
dist(ii,1:250,kk,ss) = sqrt((apert_x(1,ss)-X(ii,1:250)).^2+(apert_y(1,ss)-Y(ii,1:250)).^2)+sqrt((X(ii,1:250)-apert_x(1,kk)).^2+(Y(ii,1:250)-apert_y(1,kk)).^2);
end
end
end
for ss = 2:23
for ii = 1:no_gridsx
dist(ii,1:250,kk,ss) = sqrt((apert_x(1,ss)-X(ii,1:250)).^2+(apert_y(1,ss)-Y(ii,1:250)).^2)+sqrt((X(ii,1:250)-apert_x(1,kk)).^2+(Y(ii,1:250)-apert_y(1,kk)).^2);
end
end
end
for ss = 24
for ii = 1:no_gridsx
dist(ii,1:250,kk,ss) = sqrt((apert_x(1,ss)-X(ii,1:250)).^2+(apert_y(1,ss)-Y(ii,1:250)).^2)+sqrt((X(ii,1:250)-apert_x(1,kk)).^2+(Y(ii,1:250)-apert_y(1,kk)).^2);
end
end
end
Image Analyst on 22 Aug 2019
I rescued this from the spam quarantine.

Guillaume on 22 Aug 2019
One way:
for ss = 1:24
kk_s = kk_indices{(ss > 1) + (ss > 23) + 1}; %(ss>1) + (ss>23) + 1 will be 1 for ss = 1, 2 for ss = 2:23 and 3 for ss = 24
for kk = kk_s
end
end
Note that the
for s = 1
%some code
end
you wrote is pointless. It is the same as the more straighforward
ss = 1
%some code