필터 지우기
필터 지우기

Calculating a seperated sum from a vector.

조회 수: 1 (최근 30일)
Benedikt Wessel
Benedikt Wessel 2019년 6월 2일
답변: Star Strider 2019년 6월 2일
Hello everybody.
A=[1,2,3,4,5,6,7,8,9,10] % not a fixed size, can be build with n*5
How can I build the sum of five numbers? I know how to do it, when the length of the vector is fixed:
a=sum(A(1:5),2)
b=sum(A(6:10),2)
Can you help me putting this operation into a for loop, so that I can do it on every size of the vector?
Tahnks.

채택된 답변

Star Strider
Star Strider 2019년 6월 2일
If you want to sum consecutive blocks of elements, no explicit looop is necessary. You can just use the reshape (link) function, then do the summation.
N = 12; % Create Vector Length
A = 1:N; % Create Data
len = 5; % Number OF Elements To Sum In Each Segment
You did not say how you wanted to handle elements that were not part of a segment equal to 5, so here are two possibilities:
mtx = reshape(A(1:len*fix(numel(A)/len)), len, []); % Discard Elements > Multiple Of ‘len’
or:
mtx = reshape([A(:);zeros(len*ceil(numel(A)/len)-numel(A),1)], len, []); % Zero-Pad Elements > Multiple Of ‘len’
then the summation is simply:
s = sum(mtx);
You can put the ‘mtx’ assignments within the sum argument to create a single line of code. I created ‘mtx’ separately for convenience here.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by