Arijeet Dutta
Arijeet Dutta

Reputation: 45

How to sum individual elements MATLAB

Suppose I have a row matrix [a1 a2 a3 a4 .. an] and I wish to achieve each of the following in MATLAB

    1) 1+a1
    2) 1+a1+a2
    3) 1+a1+a2+a3
    4) 1+a1+a2+a3+a4
....
     1+a1+a2+...+an

How shall I get them?

Upvotes: 0

Views: 63

Answers (1)

LowPolyCorgi
LowPolyCorgi

Reputation: 5188

This is the purpose of the cumsum function. If A is a vector containing the elements [a1 a2 a3 .. an] then

B = cumsum([1 A]);

contains the terms you are searching for. Another possibility is

B = 1 + cumsum(A);

Edit

If you don't want to use a built-in function like cumsum, then the simpler way to go is to do a for loop:

% Consider preallocation for speed
B = NaN(numel(A),1);   

% Assign the first element
B(1) = 1 + A(1);

% The loop
for i = 2:numel(A)
  B(i) = B(i-1) + A(i);
end

or, without preallocation:

B = 1 + A(1);
for i = 2:numel(A)
  B(end+1) = B(end) + A(i);
end

Best,

Upvotes: 1

Related Questions