Averaging Values in a Matrix with Nans
1 view (last 30 days)
Show older comments
I recently posted about something similar yesterday and thought I figured it out only to realize my output wasnt right. Im attempting to average every 2 values in a column such that a 20 x 7 matrix becomes a 10x7 matrix of averaged values. I wrote the below code with an aritrary 20 x 7 matrix as a tester however this only returns a matrix of answers that are all the same. This code below using the provided matrix for example returns a 10x7 matrix of -1's. Is there any way around this?
Edit: I kow this sample only has one "nan' value in it but future applications of this potentially have many more!
Strain=[-1,0,2,-1,-1,-1,-1;-1,1,1,1,nan,-1,-1;-1,2,2,1,-2,-2,-1;0,2,1,-1,-1,0,0;-1,1,3,-1,-2,0,-2;0,0,1,2,-1,0,-1;1,1,0,1,-1,1,-1;-1,2,1,1,-1,0,1;-2,-1,0,-1,-5,0,0;-2,1,0,1,0,0,-1;-2,1,2,1,0,-1,-1;1,1,2,0,-1,0,-2;0,3,0,2,-2,-1,-1;-2,2,1,-1,-2,0,0;-4,-1,-1,1,1,1,0;-1,2,3,1,-1,1,0;-1,1,1,1,-1,1,-1;-1,1,1,2,-1,1,0;-2,0,1,0,0,0,-1;0,2,2,1,-3,-2,-1]
endCondition=20;
for j=1:size(Strain,2)
n=1
for i=1:2:endCondition
Test(n,j)=mean(Strain(~isnan(Strain(i:i+1,j))))
n=n+1;
end
end
0 Comments
Accepted Answer
KSSV
on 12 May 2020
Edited: KSSV
on 12 May 2020
Strain=[-1,0,2,-1,-1,-1,-1;-1,1,1,1,nan,-1,-1;-1,2,2,1,-2,-2,-1;0,2,1,-1,-1,0,0;-1,1,3,-1,-2,0,-2;0,0,1,2,-1,0,-1;1,1,0,1,-1,1,-1;-1,2,1,1,-1,0,1;-2,-1,0,-1,-5,0,0;-2,1,0,1,0,0,-1;-2,1,2,1,0,-1,-1;1,1,2,0,-1,0,-2;0,3,0,2,-2,-1,-1;-2,2,1,-1,-2,0,0;-4,-1,-1,1,1,1,0;-1,2,3,1,-1,1,0;-1,1,1,1,-1,1,-1;-1,1,1,2,-1,1,0;-2,0,1,0,0,0,-1;0,2,2,1,-3,-2,-1]
M = zeros(10,7) ;
[m,n] = size(Strain) ;
count = 0 ;
for i = 1:2:m
count = count+1 ;
M(count,:) = nanmean(Strain(i:i+1,:)) ;
endfor
Without loop:
Strain=[-1,0,2,-1,-1,-1,-1;-1,1,1,1,nan,-1,-1;-1,2,2,1,-2,-2,-1;0,2,1,-1,-1,0,0;-1,1,3,-1,-2,0,-2;0,0,1,2,-1,0,-1;1,1,0,1,-1,1,-1;-1,2,1,1,-1,0,1;-2,-1,0,-1,-5,0,0;-2,1,0,1,0,0,-1;-2,1,2,1,0,-1,-1;1,1,2,0,-1,0,-2;0,3,0,2,-2,-1,-1;-2,2,1,-1,-2,0,0;-4,-1,-1,1,1,1,0;-1,2,3,1,-1,1,0;-1,1,1,1,-1,1,-1;-1,1,1,2,-1,1,0;-2,0,1,0,0,0,-1;0,2,2,1,-3,-2,-1]
s = reshape(Strain',7,2,[]) ;
s = permute(s,[2 1 3]) ;
iwant = squeeze(nanmean(s))' ;
More Answers (1)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!