# Creating an array of partial sums of certain array

10 Ansichten (letzte 30 Tage)
Sheet am 20 Feb. 2023
Kommentiert: Sheet am 21 Feb. 2023
Suppose I have an initial array [a1 a2 a3 a4 a5]. Then I have to create an array = [a1, a2, a3, a4, a5, a1+a2, a2+a3, a3+a4, a4+a5, a1+a2+a3, a2+a3+a4, a3+a4+a5, a1+a2+a3+a4, a2+a3+a4+a5, a1+a2+a3+a4+a5]. Array has total 5*(5+1)/2 =15 elements. How to do it?
I need to extend it to any finite (say n) no. of elements in the initial array so that the resulting array has n(n+1)/2 elements.
Thank you.
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Dyuman Joshi am 20 Feb. 2023
Here is an approach, however I am not sure how fast this will be for a large n
y=[1 2 3 4 5 6];
n=numel(y);
z=cell(1,n);
for k=1:n
end
out=[z{:}]
out = 1×21
1 2 3 4 5 6 3 5 7 9 11 6 9 12 15 10 14 18 15 20 21
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

John D'Errico am 20 Feb. 2023
Bearbeitet: John D'Errico am 20 Feb. 2023
For example, consider the vector (I've used syms here, so you can see that it works, and generate the correct terms. Had a been any numeric vector, it would work as well.)
n = 5;
syms a [1,n]
a
a =
Now what happens when you multiply that vector by an array, of the form
diag(a)*tril(ones(n))
ans =
Does that look somewhat like what you anted? Not exactly, I know. But, is it close?
So then, what would cumsum do?
cumsum(diag(a)*tril(ones(n)))
ans =
So the list of terms that you are looking to find are in the lower half of that matrix. Can you extract them trivially? Again, we can use find and tril. Putting it all together now, we have
ind = find(tril(ones(n)));
A = cumsum(diag(a)*tril(ones(n)));
A = A(ind)
A =
How many terms are in that result?
numel(A)
ans = 15
So now try it out.
a = 1:7; % we expect to see 28 total terms in the result.
n = numel(a);
ind = tril(ones(n)) == 1;
A = cumsum(diag(a)*tril(ones(n)));
A = A(ind)
A = 28×1
1 3 6 10 15 21 28 2 5 9
numel(A)
ans = 28
##### 3 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
John D'Errico am 20 Feb. 2023
Bearbeitet: John D'Errico am 20 Feb. 2023
Yes. find was not necessary there. I am not at all sure what size arrays are involved. We were never told that information.
Sheet am 21 Feb. 2023
Thank You.

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by