How to modify an array's elements using another element?

I need to write a for loop that will set each array element in bonusScore to the sum of itself and the next element (except for the last element which stays the same). Why why does my code yield these (incorrect) output numbers? What should I do to fix my code?
function bonusScores = CombineScores(numberScores, userScores)
for i = 1:numbersScores;
userScores(1) = userScores(1) .* 2 + userScores(2);
userScores(2) = userScores(2) .* 2 + userScores(3);
userScores(3) = userScores(3) .* 2 + userScores(4);
bonusScores = userScores;
end
end
Input: CombineScores(4, [10, 20, 30, 40]) Output: ans = 1800, 1960, 1080, 40

2 件のコメント

KALYAN ACHARJYA
KALYAN ACHARJYA 2018 年 10 月 20 日
編集済み: KALYAN ACHARJYA 2018 年 10 月 20 日
What results you are expecting on above-mentioned input?
Input: CombineScores(4, [10, 20, 30, 40])
Matthew Burton
Matthew Burton 2018 年 10 月 21 日
I am expecting...
Output: [30, 50, 70, 40]
Thanks.

サインインしてコメントする。

 採用された回答

Bruno Luong
Bruno Luong 2018 年 10 月 21 日

3 投票

Fix code:
function bonusScores = CombineScores(numberScores, userScores)
for i = 1:numberScores-1
userScores(i) = userScores(i) + userScores(i+1);
end
bonusScores = userScores;
end
Try
>> CombineScores(4, [10, 20, 30, 40])
ans =
30 50 70 40

1 件のコメント

Matthew Burton
Matthew Burton 2018 年 10 月 23 日
Thanks! Yes, I see... I just needed that last line.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by