问题
I have one big 5D matrix and I want to split the matrix in 10 parts containing 57 rows and 92 columns and then take the means of each matrix (10 matrices) while ignoring zeros. I am trying this one example. While applying the second loop, Undefined function M_ii
error is showing in Matlab.
val = zeros(57,92,1,1,10);
% Create N matrices
N = 10;
for i = 1:N
eval(sprintf('M_%d = val(:,:,1,1,%d);', i, i));
end
for i = 1:10
M_i(M_i==0)=NaN;
Mean_1=mean(M_i);
mean_1=mean(Mean_1,2);
end
回答1:
You cannot expect variable names to be generated/changed like that and of course you'd need another ugly way to do that; just like the one you used to create them in the first place. So please never ever make dynamic variables. If you ever think that you need dynamic variables, you need to think again.
You can directly use mean along the first and second dimensions. You'd need the omitnan
flag after replacing zeros with NaN
to exclude zeros from the computation of mean.
val(val==0) = NaN;
mean_1 = mean(val,1,'omitnan');
mean_2 = mean(val,2,'omitnan');
By the way, to remove singleton dimensions (3rd and 4th in your provided example), you can use squeeze.
来源:https://stackoverflow.com/questions/46742216/how-to-convert-zeros-into-nan-and-then-take-mean-afterwards