Optimization of matlab code
조회 수: 3 (최근 30일)
이전 댓글 표시
I am relatively new in MATLAB and my major problem is optimization. My code seems to run very slowly and I can't think of any way to make it faster. All my arrays have been preallocated. S is a large number of element (say 1500 element, for example). i know my code runs slowly because of the "for k=1:S" but i cant think of another way to perform this loop at a relatively fast speed. Just to explain my code, i have a set of points and for each point i want to obtain the predicted_value and its predicted_error. Can i please get help because it takes hours to run (when S = 1000 elements, for example)
[M,~] = size(Sample2000_X);
[N,~] = size(Sample2000_Y);
[S,~] = size(Prediction_Point);
% Speed Preallocation
Distance = zeros(M,N);
Distance_Prediction = zeros(M,1);
Semivariance = zeros(M,N);
semivariance_Prediction = zeros(M,1);
Predicted_Value00 = zeros(S,1);
Predicted_Error = zeros(S,1);
for k=1:S
for i=1:M
for j=1:N
Distance(i,j) = sqrt(power((Sample2000_X(i)-Sample2000_X(j)),2)+power((Sample2000_Y(i)-Sample2000_Y(j)),2));
end
Distance_Prediction(i,1) = sqrt(power((Prediction_Point(k,1)-Sample2000_X(i)),2)+power((Prediction_Point(k,2)-Sample2000_Y(i)),2));
end
Lagrange_Column = ones(M,1);
Lagrange_Row = [ones(1,N),0];
for i=1:M
for j=1:N
if (Distance(i,j) == 0)
Semivariance(i,j) = 0;
elseif (Distance(i,j) > Range00)
Semivariance(i,j) = Nugget00+Sill00;
else
Semivariance(i,j) = Nugget00+Sill00*((3*0.5*(Distance(i,j)/Range00))-(0.5*power((Distance(i,j)/Range00),3)));
end
end
if (Distance_Prediction(i) == 0)
semivariance_Prediction(i) = 0;
elseif (Distance_Prediction(i) > Range00)
semivariance_Prediction(i) = Nugget00+Sill00;
else
semivariance_Prediction(i) = Nugget00+Sill00*((3*0.5*(Distance_Prediction(i)/Range00))-(0.5*power((Distance_Prediction(i)/Range00),3)));
end
end
Semivariance_Prediction = [semivariance_Prediction;ones()];
Semivariance_Lagrange = [Semivariance,Lagrange_Column;Lagrange_Row];
weights = Semivariance_Lagrange\Semivariance_Prediction;
Weights = weights(1:end-1,:);
Predicted_Value00(k,1) = sum(Sample2000_Z.*Weights);
Predicted_Error(k,1) = sum(Semivariance_Prediction.*weights);
end
댓글 수: 0
답변 (2개)
Jos (10584)
2016년 5월 26일
Pre-allocate all your outputs before the loop.
Distance = zeros(M,N)
...
The editor should have given you a warning " The variable .. appears to be growing inside a loop". Did you notice the small red underlining in the editor?
댓글 수: 3
Steven Lord
2016년 5월 26일
Try to profile your code with a small data set to identify potential bottlenecks then improve or eliminate the bottlenecks identified during the previous step.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Surrogate Optimization에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!