How can I find the cumulative sum of a vector without using the cumsum funtion or any loops

40 次查看(过去 30 天)
If I have [4 -2 6 1 2], how I find the cum sum of this vector without using the cumsum function or loops or any other functions. I method I am allowed to use is just simple vector operations (sum,diff,etc) functions.
  3 个评论

请先登录,再进行评论。

回答(4 个)

Tim Berk
Tim Berk 2017-9-19
I know this is your homework, but I thought it was a fun problem.
You can do this with matrix manipulations:
A = [4 -2 6 1 2]
B = tril(ones(length(A)))
C = A.*B
cum_sum = sum(C,2)

Stephen23
Stephen23 2017-9-19
>> A = [4,-2,6,1,2];
>> sum(triu(A(:)*ones(1,numel(A))),1)
ans =
4 2 8 9 11
>> cumsum(A)
ans =
4 2 8 9 11
  6 个评论
Tim Berk
Tim Berk 2017-9-20
"You would also need to transpose B to get the right answer:"
That's right. Or using triu instead of tril.
Since you seem to be interested in small details: technically your code does not work for "any size or orientation array". It only gives the right answer for row vectors, as the answer is always a row vector. If you input a column vector, the answer is the transpose of the actual cumsum. If you input a 2D array the answer is a row vector that has nothing to do with the cumsum of that array.
The cumulative sum of
A = [1 2; 3 4]
Should be
[1 2; 4 6]
or
[1 3; 3 7]
depending on which dimension we are taking the cumulative sum over. Neither of our methods gives such an answer.
Stephen23
Stephen23 2017-9-20
编辑:Stephen23 2017-9-21
@Tim Berk: Good catch, you are right, I was wrong that my code works with "any size ... input array".

请先登录,再进行评论。


Andrei Bobrov
Andrei Bobrov 2017-9-20
sum(hankel([zeros(numel(A)-1,1);A(1)],A))

the cyclist
the cyclist 2017-9-20
Perhaps the only solution which will not raise the eyebrows of OP's instructor:
A = [4 -2 6 1 2];
nA = numel(A);
cumA = zeros(1,nA);
for ia = 1:nA
cumA(ia) = sum(A(1:ia));
end
:-)
  2 个评论
Tim Berk
Tim Berk 2017-9-20
Depends on whether it is a course on matlab or on vector calculus.
In any case, a for loop might not be a good idea for large nA. If I were to instruct a course on matlab, I would prefer students to work with the fastest solution.
the cyclist
the cyclist 2017-9-21
The for loop is fast for moderately large nA. In fact, it is the fastest of the three solutions that I tried (in admittedly little testing on my part). For very large nA, there might also be memory issues for some solutions.
rng default
N = 5000;
NR = 100;
A = rand(1,N);
tic
for ii = 1:NR
nA = numel(A);
cumA1 = zeros(1,nA);
for ia = 1:nA
cumA1(ia) = sum(A(1:ia));
end
end
toc
tic
for ii = 1:NR
B = tril(ones(length(A)));
C = A.*B;
cumA2 = sum(C,2);
end
toc
tic
for ii = 1:NR
cumA3 = sum(triu(A(:)*ones(1,numel(A))),1);
end
toc

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by