Averaging Values in a Matrix with Nans

4 次查看(过去 30 天)
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

采纳的回答

KSSV
KSSV 2020-5-12
编辑:KSSV 2020-5-12
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))' ;

更多回答(1 个)

Brian Hemmat
Brian Hemmat 2020-5-12
I think this is what you want to do:
mean(Strain,2,'omitnan')

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by