How do I run through a vector combining every 3 values together

Hi,
What I would like to do is run through a vector and combine every say 3 values together with some function (say the sum() function) and output a new vector. eg. A = [1 1 1 2 2 2 3 3 3]; Anew = A[sum(1:3), sum(4:6) sum(7:9)] = [1+1+1 2+2+2 3+3+3] = [3 6 9] I would like to be able to do this regardless of the length of A. Obviously I can do it in a loop, but wondered whether there was a more efficient syntax/implementation.
Thanks, Chris

4 个评论

Does A always start with 1 and repeats the value for as many times the block is long and then increases by one?
Anyway, for this particular A:
accumarray(A,A)
Perhaps
accumarray(A(:),A(:))
Each row forms one set of subscripts so you usually need to transform the row vector A in to a column vector.

请先登录,再进行评论。

 采纳的回答

A = [1 1 1 2 2 2 3 3 3];
B=reshape(A,3,[]);
C=sum(B)
Added error checking
A=[1 1 1 2 2 2 3 3 3];
N=2;
try
B=reshape(A,N,[]);
C=sum(B);
catch
disp(lasterr);
end

3 个评论

+1: Very direct, very efficient.
Maybe it is necessary to catch inputs, whose length is not a multiple of 3.
or:
if ~mod(numel(a),3)
%do good stuff
else
%complain
end

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Simulink 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by