Adding certain elements in an input vector and outputting a new vector with those sums.

1 回表示 (過去 30 日間)
Coleman
Coleman 2022 年 10 月 4 日
回答済み: Ergin Sezgin 2022 年 10 月 4 日
I am having trouble with writing a function where the input is a vector. This vector will be taken and every two elements will be added together and transfered into an output vector. For example if the input vector is [1, 2, 3, 4, 5, 6] then the output would be [3, 7, 11]. If the input vector has an odd number of elements then the final element of the vector is multiplied by 2. For example, the input vector is [1, 2, 3] then the output would be [3, 6]. Thanks for your help!
  1 件のコメント
the cyclist
the cyclist 2022 年 10 月 4 日
Please read this guide about getting help with homework, and edit your question accordingly.

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

回答 (1 件)

Ergin Sezgin
Ergin Sezgin 2022 年 10 月 4 日
Hello Coleman,
It is relatively an easy task and seems like a homework so let me just help on the algorithm instead of the code.
You can use length function and mod function to determine whether the vector has odd or even number of elements. Then you can use reshape function to transform your row vector into a 2D matrix which has only 2 rows and unlimited number of columns. Then simply use sum function to get the sum of consecutive elements which are now in same column but at different rows. If your array has odd number of elements, multiply your raw arrays last element by two and add it to the end of your sum array and that's all.
Good luck

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by