How to sum all other lines in MATLAB

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

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

eg,

1 1 1 2 2 2 4 4 4 

say i = 2, I want to get the following:

 5 5 5 

I can do this by summing all the rows and then subtracting row i, but I want to know if there is a faster way to use the MATLAB index / select syntax.

+4
source share
3 answers

It seems that summing all the lines and then subtracting the line i is much faster:

 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. 
+7
source

To add to the performance considerations of previous authors. The nate solution 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 indexing issue as described in the quoted question.

Consider the following simple tests, following the previous structure:

 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. 
+4
source

Well, you can 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 pointed out, as good as it might seem, it is actually much slower than just subtracting one line, which I advise you not to use.

+3
source

Source: https://habr.com/ru/post/1447867/


All Articles