How to make my code run faster?

I'm new to matlab and this is one of the very first functions I wrote. My function works very well except that it's very slow (~27 seconds). How can I take advantage of Matlab's syntax to better optimize it?
function [ amin,bmin,cmin ] = perm( x,y,xmin )
A=(1:0.1:9);
B=(4:0.15:16);
C=(0.003:0.0005875:0.05);
result = 0.0;
amin = 15;
bmin = 16;
cmin = 0.05;
rmin = 1000;
temp = 0;
for i=1:81
for j=1:81
for k=1:81
result = -A(k)* erf((x-xmin)*C(i))+B(j);
Error = minus(y,result).^2;
temp = norm(Error);
if temp < rmin;
rmin = temp;
amin = A(k);
bmin = B(j);
cmin = C(i);
end
end
end
end
end

 採用された回答

Roger Stafford
Roger Stafford 2013 年 1 月 22 日

1 投票

If you ignore the limits you have placed on A and B, and you want to do this minimization without using matlab's optimization functions, you can take advantage of the fact that your expression is linear in A and B and thereby cut down the number of iterations from 81^3 to only 81 as C varies. This is because, for any given value of C, the optimum values for A and B can be directly calculated as given in the code below. This the linear regression technique.
function [amin,bmin,cmin] = perm(x,y,xmin)
dmax = -inf;
ym = mean(y);
C=(0.003:0.0005875:0.05);
for i = 1:length(C)
ei = erf((x-xmin)*C(i));
em = mean(ei);
d = (sum((y-ym).*(ei-em)))^2/sum((ei-em).^2);
if d > dmax
dmax = d;
cmin = C(i);
end
end
ei = erf((x-xmin)*cmin);
em = mean(ei);
amin = -sum((y-ym).*(ei-em))/sum((ei-em).^2);
bmin = ym+amin*em;
Instead of the above you can use the above -d as your objective function to be minimized and call on one of the optimization routines to find the best C value. Afterwards you can calculate A and B as above.

1 件のコメント

Ali
Ali 2013 年 1 月 23 日
Thank you, this was very helpful

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2013 年 1 月 22 日

0 投票

The general rule applies for all computer languages and the real life also:
Avoid repeated calculations!
rmin2 = rmin * rmin;
for i=1:81
c1 = erf((x-xmin)*C(i));
for j=1:81
for k=1:81
result = -A(k)* c1 +B(j);
Error = (y - result) .^ 2; % Is y a vector?
temp = sum(Error .* Error); % SQRT is more expensive then squaring
if temp < rmin2
rmin = temp;
rmin2 = rmin * rmin;
amin = A(k);
bmin = B(j);
cmin = C(i);
end
end
end
end

2 件のコメント

Ali
Ali 2013 年 1 月 23 日
thank you
Ali
Ali 2013 年 1 月 23 日
yes, y is a vector

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by