Joh Dsd
Joh Dsd

Reputation: 9

make the following matlab code faster

function c foo(a, b)
     for ii = [1 3 4 5]
          c = a(:,ii) +  b(:,ii);
     end
return

Can someone explain what this is doing? Is it adding column 1 of a with column 1 of b, then same thing for columns 3,4,5? Should it be c+= ? Otherwise it's just overriding the last sum. I'm not too familiar with matlab, does this code make any sense? Can anyone see any ways to make this faster?

Upvotes: 0

Views: 49

Answers (1)

user2271770
user2271770

Reputation:

If the code does what is supposed to do (yes, it does overwrite previous results, and returns only the last sum) the the fastest way to do this is:

function c foo(a, b)
         c = a(:,5) + b(:,5)
end

If it's supposed to add the columns and "join" them one next to another, one may use the indexing directly:

function c foo(a, b)
         ix = [1 3 4 5];
         c  = a(:,ix) + b(:,ix);
end

Upvotes: 2

Related Questions