필터 지우기
필터 지우기

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