how to reduce the use of repeated for loops as i explained below???
    5 次查看(过去 30 天)
  
       显示 更早的评论
    
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
to calculate the variable "dist" i used three sets of for loops. is it possible to reduce
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 kk = setdiff(1:no_receivers+1,1:3)
        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 kk = setdiff(1:no_receivers+1,ss-1: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 = 24
    for kk = setdiff(1:no_receivers+1,22: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
2 个评论
采纳的回答
  Rik
      
      
 2019-8-22
        Use a temporary variable to adapt your range. The code below show one such approach.
%intitialize for testing
no_gridsx=10;
no_receivers=26;
ss_max=24;
dist=NaN(no_gridsx,250,no_receivers+1,ss_max);
for ss = 1:ss_max
    skips=ss-1:ss+1;
    if ss==1%correct for edge cases
        skips=skips+1;
    elseif ss==ss_max
        skips=skips-1;
    end
    for kk = setdiff(1:no_receivers+1,skips)
        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
4 个评论
  Stephen23
      
      
 2019-8-23
				
      编辑:Stephen23
      
      
 2019-8-23
  
			"why did you subtract ss==24 & add ss==1 , what is the logic behind this"
(ss-1:ss+1)-(ss==24)+(ss==1)
%^^^^^^^^^^                  creates a vector, exactly like you did
%          ^^^^^^^^^         when ss==24 subtracts 1 from the vector
%                   ^^^^^^^^ when ss==1 adds 1 to the vector
With setdiff this provides exactly the vectors described on the first three lines of your question.
更多回答(0 个)
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Deep Learning Toolbox 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



