defining the mean of a values inside a matrix
Show older comments
Greetings,
I was trying to find a way to find the mean of the values inside the matrix. For example, [1,2,3,4,5,6] I want to find the average between 1 & 2/ 2&3/3&4/4&5 and so on
I tried to do a for-loop but It doesnt seemt to work when I compare the values to hand calculations
z18=(-length(theta)/2+(0:length(theta)))'*h; % Travel of total 18 layers %%%% 19 values due to neutral axis
z18t=((-length(theta)/2+(0:length(theta)))'*h)/2; %% I took this approach as well but it does not work
for t=1:length(z18)
tt=max(1,(t-1));
ttt=min(length(z18), t+1);
tttt(t)=mean(z18(tt:ttt));
end
1 Comment
Walter Roberson
on 18 Apr 2021
movmean() ?
Accepted Answer
More Answers (1)
Khalid Mahmood
on 18 Apr 2021
Edited: Khalid Mahmood
on 18 Apr 2021
Further methods
1: movmean(matrix,windowsize) it calculates running mean but considers only windowsize elements
examples:
mm2=movmean(z18,2)
mm3=movmean(z18,3)
Using for loop to calculate running mean as [z18(1), (z18(1)+z18(2)/2, ( (z18(1)+z18(2) )/2+ z18(3) )/3,...]
mm=z18(1);
for p=2:length(z18)
mm(p)=(mm(p-1)+z18(p))/p;
end
8 Comments
Sufia Tanveer
on 18 Apr 2021
Wow, here I find great programmers of Matlab... Great learning here. Awesome answers in quick time
Sufia Tanveer
on 18 Apr 2021
I mean excellent answers
z18 = randi(9, [1 6])
mm=z18(1);
for p=2:length(z18)
mm(p)=(mm(p-1)+z18(p))/p;
end
mm
movmean(z18,2)
[z18(1), z18(1:end-1) + diff(z18)/2, z18(end)]
I don't think the mm code is correct at all.
Sufia Tanveer
on 18 Apr 2021
At 1st I also thought that mm code seems wrong. But it is desired sometimes to reduce values in this manner. I like that way of reducing values... It is not a mean but a way to reduce values
Khalid Mahmood
on 18 Apr 2021
Edited: Khalid Mahmood
on 18 Apr 2021
Yes, both of you are correct. Above mm code uses previous average and next value of vector, which off course reduces values. A better way to use all previous values of vector (not previous average) in moving mean is :
z18 = randi(9, [1 6]);
mm=z18(1);
for p=2:length(z18)
mm(p)=sum(z18(1:p))/p;
end
z18
1 3 5 9 9 2
mm
1 2 3 4.5 5.4 4.8333
and vectorised form is
mm=cumsum(z18)./(1:length(z18))
1 2 3 4.5 5.4 4.8333
Sufia Tanveer
on 18 Apr 2021
Its great now!
Sufia Tanveer
on 18 Apr 2021
I learnt more from comments than actual question!
Khalid Mahmood
on 19 Apr 2021
And remember, In moving mean, last value of source vector is not copied in result. It is actually calculated. So moving mean methods, movmean, mm code (to rduce in a mean way), and vectorised cumsum./[1:src] methods are actual moving mean methods. Those are just different types of moving means
Categories
Find more on Line Plots 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!