I need to compute the mean of a matrix but only for those values that are greater than a specified number. Right now I come with this idea:
Media = mean(W_tot_migl,2);
H = W_tot_migl;
H(H<LimiteInferiore) = nan;
Media_b = nanmean(H,2);
Is there any way to avoid to create another matrix H = W_tot_migl
?
For matrix H
and threshold T
you can use:
M = nanmean(H+0./(H>T),2);
in your case:
Media_b = nanmean(W_tot_migl+0./(W_tot_migl>LimiteInferiore),2);
OR calculate it yourself:
M = sum(H.*(H>T),2)./sum(H>T,2);
For your case:
Media_b = sum(W_tot_migl.*(W_tot_migl>LimiteInferiore),2)./sum(W_tot_migl>LimiteInferiore,2);
Note that both methods return NaN
if there are no values greater than the threshold in a row.
However, in general you can use accumarray
to accomplish this:
H2 = H>T;
[I,~] = find(H2);
M = accumarray(I, H(H2), [size(H,1) 1], @mean);
This method returns zero if there are no elements larger than the threshold in a row.