Effacer les filtres
Effacer les filtres

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

6 vues (au cours des 30 derniers jours)
Rahul Marwaha
Rahul Marwaha le 5 Jan 2021
Modifié(e) : Adam Danz le 6 Jan 2021
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 :)

Réponse acceptée

Adam Danz
Adam Danz le 5 Jan 2021
Modifié(e) : Adam Danz le 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

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by