简体   繁体   中英

How to find a sum 3 elements in array?

I have an array A=[a1,a2,a3, ..., aN] I would like to take a product of each 3 elements:

s1=a1+a2+a3

s2=a4+a5+a6

...

sM=a(N-2)+a(N-1)+aN

My solution:

k=size(A);
s=0;
for n=1:k
s(n)=s(n-2)+s(n-1)+s(n);
end

Error: Attempted to access s(2); index out of bounds because numel(s)=1.

Hoe to fix it?

If you want to sum in blocks , for the general case when the number of elements of A is not necessarily a multiple of the block size, you can use accumarray :

A = [3 8 5 8 2 3 4 7 9 6 4]; % 11 elements
s = 3; % block size
result = accumarray(ceil((1:numel(A))/s).', A(:));

If you want a sliding sum with a given block size, you can use conv :

A = [3 8 5 8 2 3 4 7 9 6 4]; % 11 elements
s = 3; % block size
result = conv(A(:).', ones(1,s), 'valid');

You try to calculate s by using values from s . Dont you mean s(n)=A(n-2)+A(n-1)+A(n); ? Also size returns more than one dimension on its own.

That being said, getting the 2 privous values n-2 and n-1 doenst work for n=1;2 (because you must have positive indices). You have to explain how the first two values should be handeled. I assume either 0 for elements not yet exisiting

k=size(A,2); %only the second dimension when A 1xn, or length(A) 
s=zeros(1,k); %get empty values instead of appending each value for better performance
s(1)=A(1);
s(2)=A(2)+A(1);
for n=3:k %start at 3 
    s(n)=A(n-2)+A(n-1)+A(n);
end

or s shoult be 2 values shorter than A .

k=size(A,2);
s=zeros(1,k-2);
for n=1:k-2
    s(n)=A(n)+A(n+1)+A(n+2); 
end
  • You initialise s as a scalar with s = 0 . Then you try and index it like an array, but it only has a single element.
  • Your current logic (if fixed) will calculate this:

     s(1) = a(1)+a(2)+a(3) s(2) = a(2)+a(3)+a(4)... % 's' will be 2 elements shorter than 'a'

    So we need to be a bit wiser with the indexing to get what you describe, which is

    s(1) = a(1)+a(2)+a(3) s(2) = a(4)+a(5)+a(6)... % 's' will be a third as big as 'a'

You should pre-allocate s to the right size, like so:

k = numel(A); % Number of elements in 'A'
s = zeros( 1, k/3 ); % Output array, assuming 'k' is divisible by 3
for n = 0:3:k-3
    s(n/3+1) = a(n+1) + a(n+2) + a(n+3);
end

You could do this in one line by reshaping the array to have 3 rows, then summing down each column, this assumes that the number of elements in a is divisible by 3, and that a is a row vector...

s = sum( reshape( a, 3, [] ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM