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 个评论
Image Analyst
2017-9-13
What's wrong with the totally obvious:
theSum = 4 + -2 + 6 + 1 + 2;
That is one way that works without loops or any functions. It meets all your stated requirements. Anything wrong with it?
回答(4 个)
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
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
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.
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
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
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 Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!