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

1 view (last 30 days)
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!

Answers (1)

Ergin Sezgin
Ergin Sezgin on 4 Oct 2022
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

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!