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