Averaging Values in a Matrix with Nans

1 visualizzazione (ultimi 30 giorni)
Josh
Josh il 12 Mag 2020
Commentato: Josh il 12 Mag 2020
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

Risposta accettata

KSSV
KSSV il 12 Mag 2020
Modificato: KSSV il 12 Mag 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))' ;

Più risposte (1)

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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by