How to extract value from matrix and add a constant repeatedly?

2 views (last 30 days)
I'm trying to get my script to extract values from an array and add to a know constant and form a new array.
x = 2 % Constant
y = [1 3 2 7 8] % Array
Z1 = x + y(5);
Z2 = Z1 + y(4);
Z3 = Z2 + y(3);
% etc
As seen above the last value in the array is extracted and added to the known constant. This new value is the used to find a new constant (Z2) by adding the fourth value in the array. I need this to repeat for all values in the array from y(5) to y(1), however, in a way where the 'y' array can be of any size.
Any help is much appreciated :)

Accepted Answer

Adam Danz
Adam Danz on 5 Jan 2021
Edited: Adam Danz on 6 Jan 2021
Take the cumulative sum of y from right to left after adding 2 to the end:
x = 2; % scalar
y = [1 3 2 7 8]; % row vector
z = cumsum(fliplr(y+[zeros(1,numel(y)-1),x]))
z = 1×5
10 17 19 22 23

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!