lethalfang
October 19th, 2009, 01:01 AM
Is there a faster way to do the following operation?
For a vector, I want a new vector such that, each element in the new vector is the sum of all the elements before it in the old vector.
I can do it with this loop:
old_vector = ones(1, 10); or
old_vector = [ 1 1 1 1 1 1 1 1 1 1]
for i = 1 : length(old_vector)
new_vector(i) = sum( old_vector( 1:i ) );
end
new_vector = 1 2 3 4 5 6 7 8 9 10
But I'm having a bunch of vectors whose lengths are on the order of 10^5, and this loop is really slowing things down. I wonder if there is a fast way to do it.
Thanks in advance!
For a vector, I want a new vector such that, each element in the new vector is the sum of all the elements before it in the old vector.
I can do it with this loop:
old_vector = ones(1, 10); or
old_vector = [ 1 1 1 1 1 1 1 1 1 1]
for i = 1 : length(old_vector)
new_vector(i) = sum( old_vector( 1:i ) );
end
new_vector = 1 2 3 4 5 6 7 8 9 10
But I'm having a bunch of vectors whose lengths are on the order of 10^5, and this loop is really slowing things down. I wonder if there is a fast way to do it.
Thanks in advance!