How to sum all other rows in MATLAB
matlab, matrix, sum
Solution
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.
Problem
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.