Azzera filtri
Azzera filtri

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

6 visualizzazioni (ultimi 30 giorni)
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 :)

Risposta accettata

Adam Danz
Adam Danz il 5 Gen 2021
Modificato: Adam Danz il 6 Gen 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

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by