Dear all,
I am fairly new to matlab and struggling to write a code. I will be grateful to be given a push. For instance given a vector one to hundered, I want to take every three values and average them. Also print the output result. E.g
(1+2+3)/3 + (4+5+6)/3 + (7+8+9)/3 + .......
Thank you in advance and I appreciate your contribution.
regards
Ismaeel

2 commentaires

John D'Errico
John D'Errico le 30 Juil 2016
Unless your vector has a length that is a multiple of 3, any such solution will fail. So 100 elements will not allow you to do that.
The simple solution uses reshape and sum to solve the problem. So why not try it? You will learn by trying. So see what reshape does. How might that help you? Then think about what the sum function does.
shalipse
shalipse le 30 Juil 2016
Many thanks John.

Connectez-vous pour commenter.

 Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 30 Juil 2016
Modifié(e) : Azzi Abdelmalek le 30 Juil 2016

0 votes

A=randi(10,30,1) % Example
mean(reshape(A,3,[]))
If the length of A is not a multiple of 3
A=randi(10,38,1)
n=numel(A)
p=mod(-n,3)
A(n+1:n+p)=nan % complete with nan
out=nanmean(reshape(A,3,[]))

2 commentaires

shalipse
shalipse le 30 Juil 2016
Many thanks Azzi, that was quick... Is it possible to use a loop command with a conditional statement that would stop the computation at 99, given that no values can be added to the iteration after this.
Thank you again
shalipse
shalipse le 30 Juil 2016
Many thanks. I appreciate your time

Connectez-vous pour commenter.

Plus de réponses (2)

Andrei Bobrov
Andrei Bobrov le 30 Juil 2016

0 votes

z = accumarray(ceil((1:numel(A))'/3),A(:),[],@mean);
Image Analyst
Image Analyst le 30 Juil 2016

0 votes

Yet another way using conv() to take the moving average:
m = 1 : 33 % Create sample data.
m2 = conv(m, [1,1,1]/3, 'valid'); % Intermediate array.
output = m2(1:3:end) % Subsample to get final array.

Catégories

En savoir plus sur Signal Processing Toolbox dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by