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

1 visualización (últimos 30 días)
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!

Respuestas (1)

Ergin Sezgin
Ergin Sezgin el 4 de Oct. de 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

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by