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

 Accepted Answer

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.

More Answers (1)

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 Comments

thank you
yes, y is a vector

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!