4

I am still learning some of the advanced features in MATLAB.

I have a 2D matrix and I want to sum all rows, except for for i.

eg

1 1 1
2 2 2
4 4 4

say i = 2, I want to get this:

5 5 5

I can do it by summing all the rows, then subtracting row i, but I want to know if there is a faster way using MATLAB's indexing/selection syntax.

ljbade
  • 4,576
  • 4
  • 30
  • 35

3 Answers3

7

It seems that summing all the rows, then subtracting row i, is much faster tough:

A=rand(500);
n = randi(500);
tic
for i=1:1e3
%sum(A([1:n-1 n+1:end], :));
sum(A)-A(n,:);
end
toc

     Elapsed time is 0.162987 seconds.

A=rand(500);
n = randi(500);
tic
for i=1:1e3
sum(A([1:n-1 n+1:end], :));
end
toc

     Elapsed time is 1.386113 seconds.
bla
  • 25,846
  • 10
  • 70
  • 101
  • 1
    You have a rather fast computer, nate. What are you using? I have an i7 2.8GHz, and my results are 4 times slower than yours.. That worries me :) – angainor Nov 23 '12 at 10:20
4

To add to the performance considerations of previous authors. The solution by nate is faster, because it does not use complex matrix indexing of the second method. Complex matrix/vector indexing is very inefficient in MATLAB. I suspect this is the same problem with indexing as the one described in the cited question.

Consider the following simple tests, following the previous framework:

A=rand(500);
n = randi(500);
tic
for i=1:1e3
    B=sum(A(:, :));
end
toc
Elapsed time is 0.747704 seconds.

tic
for i=1:1e3
    B=sum(A(1:end, :));
end
toc
Elapsed time is 5.476109 seconds.   % What ???!!!

tic
id = [1:n-1 n+1:500];
for i=1:1e3
    B=sum(A(id, :));
end
toc
Elapsed time is 5.449064 seconds.
Community
  • 1
  • 1
angainor
  • 11,760
  • 2
  • 36
  • 56
3

Well, you could do it like this:

>> A = [ 1 1 1
         2 2 2
         4 4 4];
>> n = 2;
>> sum(A([1:n-1 n+1:end], :))
ans = 
    5 5 5

However, as Nate has already indicated, as nice as it may look, it's actually so much slower than just subtracting a single row that I advise against using it :)

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • @nate: hmmm...now why would it be *SO* much slower? It's a order-of-magnitude, even if you unloop the creation of the indices... – Rody Oldenhuis Nov 23 '12 at 07:27
  • It is slow because of inefficient indexing in MATLAB :) – angainor Nov 23 '12 at 08:12
  • @angainor: Yes, I saw your question/analysis the other day...have you submitted a performance bug to TMW? The slowness seems completely unneccessary... – Rody Oldenhuis Nov 23 '12 at 08:26
  • I have [reposted the question](http://www.mathworks.se/matlabcentral/answers/54522-why-is-indexing-vectors-matrices-in-matlab-very-inefficient) at matlab central. Hope someone from TMW will care to answer. – angainor Nov 23 '12 at 10:03