Drastic processing time between calling a function with a square root operation in it and simply writing the function in the script itself

2 次查看(过去 30 天)
Hi,
Basically I encountered a very large change in processing time because of where I put a sqrt function. Here is the code:
for i = 1:Rows
helloworld = i
for k = 1:Columns
for j = 1:OneExcelLength
% RO = DistanceFinder(DimLong(k),DimLat(i),OneLong(j),OneLat(j));
RO = sqrt((DimLong(k) - OneLong(j))^2 + (DimLat(i) - OneLat(j))^2);
if RO < WellRadius
ScoreMatrix(i,k) = ScoreMatrix(i,k) + LogBOPD(j);
end
end
end
end
Here, I do the square root function in the script and it runs really fast. But if instead I take out hte comment and call a function where I wrote this same sqrt line and send it paramenters and it sends back an ouput, it seems to take probably about 1000 times as long... thats not an exaguration. I was wondering why this would be?

回答(1 个)

Sean de Wolski
Sean de Wolski 2013-6-17
More than likely the matrix is preallocated in the script because it has run previously whereas the function creates a new workspace on each call.
Inside the function, do you have orange code analyzer warnings suggesting that the matrix changes size on every loop iteration?
  2 个评论
James
James 2013-6-17
The function is actually very simple and doesn't create a matrix at all... here it is: function[Distance] = DistanceFinder(LongOne,LatOne,LongTwo,LatTwo)
Distance = 0;
Distance = sqrt(((LongTwo - LongOne)^2 + (LatTwo - LatOne)^2));
end
The only difference between using the two different sets of code that I see is one calls a function while one just runs the exact same thing in the script and its actually 138 times slower to call the function.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by