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

2 Ansichten (letzte 30 Tage)
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 :)

Akzeptierte Antwort

Adam Danz
Adam Danz am 5 Jan. 2021
Bearbeitet: Adam Danz am 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

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by