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 Comments

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.

Sign in to comment.

 Accepted Answer

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 Comments

+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

Sign in to comment.

More Answers (0)

Categories

Find more on Simulink in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!