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

3 ビュー (過去 30 日間)
Rahul Marwaha
Rahul Marwaha 2021 年 1 月 5 日
編集済み: Adam Danz 2021 年 1 月 6 日
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 :)

採用された回答

Adam Danz
Adam Danz 2021 年 1 月 5 日
編集済み: Adam Danz 2021 年 1 月 6 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by