2013-07-22 2 views
1

이 코드를 작성하고 잘 작동하지만 가능하면 두 for 루프를 제거하여 최적화하고 싶습니다. 아무도 내가 어떻게 이것을 달성 할 수있는 아이디어가 있습니까? 많은 감사합니다! 외부 루프를 제거Vectorising 중첩 For 루프

for k = 1:10 
    for l = 1:num 
     L_Mid(k,l) = sum(LMat(k,1+in_point(l):out_point(l))); 
     L_Sides(k,l) = sum(LMat(k,:))-L_Mid(k,l); 
    end 
end 

첫 번째 단계 :

chosen_runs = [2:5]; 

% Configurations for each test in order 
XY = [0 1; 0 1; 0 9; 0 1; 0 2; 0 3; 0 4; 0 5; 11 12; 11 12]; 

% Inductance Matrix 
LMat = [0.0045 0.0045 0.0045 0.0044 0.0044 0.0044 0.0044 0.0044 0.0043 0.0043; 
     0.0045 0.0046 0.0046 0.0045 0.0045 0.0045 0.0045 0.0044 0.0044 0.0044; 
     0.0045 0.0046 0.0046 0.0046 0.0046 0.0046 0.0045 0.0045 0.0045 0.0045; 
     0.0044 0.0045 0.0046 0.0047 0.0047 0.0047 0.0046 0.0046 0.0046 0.0046; 
     0.0044 0.0045 0.0046 0.0047 0.0048 0.0048 0.0047 0.0047 0.0047 0.0046; 
     0.0044 0.0045 0.0046 0.0047 0.0048 0.0048 0.0048 0.0048 0.0048 0.0047; 
     0.0044 0.0045 0.0045 0.0046 0.0047 0.0048 0.0049 0.0049 0.0049 0.0048; 
     0.0044 0.0044 0.0045 0.0046 0.0047 0.0048 0.0049 0.0050 0.0049 0.0049; 
     0.0043 0.0044 0.0045 0.0046 0.0047 0.0048 0.0049 0.0049 0.0050 0.0050; 
     0.0043 0.0044 0.0045 0.0046 0.0046 0.0047 0.0048 0.0049 0.0050 0.0051]; 

% Declaration of Variables 
runs = chosen_runs; 
num = length(runs); 
in_point = zeros(num,1); 
out_point = zeros(num,1); 
L_Mid = zeros(10,num); 
L_Sides = zeros(10,num); 

%%%%%%%%%%%%%%%%%%%%%%%%%% 

in_point = XY(runs,1); % Creates a column vector each row of which is the in_point for a chosen run 
out_point = XY(runs,2); % Creates a column vector each row of which is the out_point for a chosen run 

in_point 
out_point 

for k = 1:10 
    for l = 1:num 

     L_Mid(k,l) = sum(LMat(k,1+in_point(l):out_point(l)));  % Creates a matrix, each column of which is the inductance (in between current leads) for a chosen run, each row is a different layer in the solenoid. 
     L_Sides(k,l) = sum(LMat(k,:))-L_Mid(k,l); % Creates a matrix, each column of which is the inductance (either side of the current leads) for a chosen run, each row is a different layer in the solenoid. 

    end 
end 

L_Mid 
L_Sides 
+1

[짧은 예제] (http://sscce.org/)로 최소화 할 수 있습니까? –

답변

3

그래서이 코드를 벡터화 할

for l=1:num 
    L_Mid(:,l)=sum(LMat(:,1+in_point(l):out_point(l)),2); % Using the dim input to sum 
    L_Sides(:,l) = bsxfun(@minus,sum(LMat,2),L_Mid(:,l)); % Using bsxfun to subtract 
end 

다음 단계 L_Sides는 한 번의 작업으로 만들 수 있습니다

for l=1:num 
    L_Mid(:,l)=sum(LMat(:,1+in_point(l):out_point(l)),2); % Using the dim input to sum 
end 

L_Sides = bsxfun(@minus,sum(LMat,2),L_Mid); 

e in_point (l)의 길이 : out_point (l)은 가변적이며, 이것을 벡터화하는 깔끔한 방법은 없다. ! 아무도 내가 싶어요 좋은 방법은) 알고있어, 당신은 그대로두고, 또는이 사용할 수 있습니다

L_Mid2 = arrayfun(@(x) ... 
    sum(LMat(:,1+in_point(x):out_point(x)),2), 1:length(in_point),'uniformoutput',false); 
L_Mid2=cat(2,L_Mid2{:}) 

을하지만 아무도 성능 이점이 없을 것이며, 무슨 일이 일어나고 있는지 덜 분명하다 , 그래서 나는이 코드를 사용하지 않을 것이다.

+0

아주 우아 하구나 휴! 내가 감동! 고맙습니다 – Howard