Adds one element in vector from another, by position in array

조회 수: 4 (최근 30일)
William Taylor
William Taylor 2020년 12월 23일
답변: Walter Roberson 2020년 12월 23일
Say I have a vector 'x' that is [1:100], and I want to create a function that creates a new vector 'y' that is the sum of x(n+2)+x(n+3) at each position (n) of x (beginning at 1 and moving through the vector). What would this function look like?
This is my attempt at the function, but it does not work
for i=1:size(x)
y(i) = [x(i+2)+x(i+3)]
...
end
Thank you for any help!

채택된 답변

Stephen23
Stephen23 2020년 12월 23일
x = 1:100; % superfluous square brackets removed.
y = x(3:end-1)+x(4:end) % the MATLAB way.
y = 1×97
7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 12월 23일
y = x((1:end-3)+2) + x((1:end-3)+3)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by