Rinad Rama
Rinad Rama

Reputation: 61

High time complexity reduction of the matlab code

I am trying to run this piece of code in matlab but it has a high complexity despite that matlab is very slow with for loops. Could somewhat please help me to optimize the code below.

for k=1:th
    for i=1:D-1
        for j=i+1:D
            if(dist(j,k)>dist(i,k))
                t=ClassP1(k,i);
                ClassP1(k,i)=ClassP1(k,j);
                ClassP1(k,j)=t;
            end
        end
    end
end

where

size(ClassP1)=20x4276

size(dist)=4276x20

Thank you a lot in advance

Rinadi

Upvotes: 0

Views: 169

Answers (1)

Bas Swinckels
Bas Swinckels

Reputation: 18488

You might be able to remove the outer loop over k like so (untested since I don't have your data, might need some tweaking):

for i = 1:D-1
    for j = i+1:D
        iswap = find(dist(j, 1:th) > dist(i, 1:th));
        ClassP1(iswap, [i, j]) = ClassP1(iswap, [j, i])
    end
end

I am not sure if this saves a lot in readability or in speed.

But what is your goal? It seems that you are doing something like sorting the matrix ClassP1 based on the matrix dist (but not exactly). Maybe there is a better solution using [~, idx] = sort(dist) and then ClassP1(??, idx) = whatever.

Upvotes: 2

Related Questions