Info

This question is closed. Reopen it to edit or answer.

Is it possible to speed up this code?

1 view (last 30 days)
loop
loop on 15 Nov 2013
Closed: MATLAB Answer Bot on 20 Aug 2021
Probably the right question should be, how can I speed up this code. All help is much appreciated
N = 100
x_1 = linspace(0,1,N)
x_2 = linspace(0,1,N)
x_3 = linspace(0,1,N)
x_4 = linspace(0,1,N)
x_5 = linspace(0,1,N)
x_6 = linspace(0,1,N)
x_10=.5;x_20=.5;x_30=.5;x_40=.5;x_50=.5;x_60=.5;
objective = zeros(N,N,N,N,N,N);
distance = zeros(N,N,N,N,N,N);
for i = 1:N
for j = 1:N
for k = 1:N
for ii = 1:N
for jj = 1:N
for kk = 1:N
theta = [x_1(i) x_2(j) x_3(k) x_4(ii) x_5(jj) x_6(kk)];
objective = relevant_func(theta);
distance = ( (x_1(i) - x_10)^2 + (x_2(j) - x_20)^2 + (x_3(k) - x_30)^2 + (x_4(ii) - x_40)^2 + (x_5(jj) - x_50)^2 + (x_6(kk) - x_60)^2 )^(1/2);
end
end
end
end
end
end
Not real numbers, just to show the code.
  2 Comments
Doug Hull
Doug Hull on 15 Nov 2013
Why are you making a six dimensional matrix with 1,000,000,000,000 elements? Is this really a good idea?
Jan
Jan on 15 Nov 2013
It seems like this code is too much simplified. None of the calculations is stored anywhere, so the loops can be omitted.
Optimizing a simplified code is not meaningful. Better let the profile or some TIC/TOCs identify the bottleneck. If e.g. relevant_func() consumes 96% of the computing time, changing ^(1/2) to sqrt() cannot be a significant improvement.

Answers (1)

Walter Roberson
Walter Roberson on 15 Nov 2013
Equivalent but faster code:
theta = [1 1 1 1 1 1];
objective = relevant_func(theta);
distance = sqrt( sum((theta - [x_10 x_20 x_30 x_40 x_50 x_60]).^2) );
With no loops.

Community Treasure Hunt

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

Start Hunting!