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

1 次查看(过去 30 天)
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 个)

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 CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by