Reputation: 367
I have an array as follows:
arr=[2 3 4 5 6 7 8 9 1 2 3 4];
How can I get the average of each two columns, so that the result is:
ans=[2.5 4.5 6.5 8.5 ...];
Upvotes: 0
Views: 105
Reputation: 8401
Convert it into a two-row matrix using reshape
, sum
, and divide-by-2:
>> arr=[2 3 4 5 6 7 8 9 1 2 3 4];
>> arrbar = sum(reshape(arr,2,[]))/2
arrbar =
2.5000 4.5000 6.5000 8.5000 1.5000 3.5000
Augmenting the solution per your comments to this answer, we can guard against odd lengths with a little indexing trick:
>> arrbar = sum(reshape([arr,arr(end:end-(mod(end,2)==0))],2,[]))/2
arrbar =
2.5000 4.5000 6.5000 8.5000 1.5000 3.5000
>> arr=[2 3 4 5 6 7 8 9 1 2 3 4 6];
>> arrbar = sum(reshape([arr,arr(end:end-(mod(end,2)==0))],2,[]))/2
arrbar =
2.5000 4.5000 6.5000 8.5000 1.5000 3.5000 6.0000
The extra indexing appends the final element for odd lengths so the final average is simply the final element.
Upvotes: 3
Reputation: 1389
How about using convolution?
arr=[2 3 4 5 6 7 8 9 1 2 3 4];
arr2=[1 1];
A=conv(arr,arr2)/2;
mean2=A(2:2:end-1)
plot(mean2)
If your array number is not always even, and you want to add final element at the end of the result array when array number is odd,
arr=[2 3 4 5 6 7 8 9 1 2 3 4 6];
arr2=[1 1];
A=conv(arr,arr2)/2;
if mod(length(arr),2) == 1;
mean2=[A(2:2:end-1) arr(end)]
else
mean2=[A(2:2:end-1)]
end
plot(mean2)
Upvotes: 0