如何将零转换为NaN,然后​​取平均值 [英] How to convert zeros into NaN and then take mean afterwards

查看:95
本文介绍了如何将零转换为NaN,然后​​取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的5D矩阵,我想将矩阵分成10个部分,包含57行和92列,然后在不考虑零的情况下采用每个矩阵(10个矩阵)的均值.我正在尝试这个例子.在应用第二个循环时,在Matlab中显示Undefined function M_ii错误.

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

推荐答案

您不能期望像这样生成/更改变量名,当然您需要

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.

您可以在第一个和第二个之间直接使用 mean 第二维度.在用NaN替换零之后,需要omitnan标志从平均值计算中排除零.

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');


顺便说一句,要删除单例尺寸(在您提供的示例中为第3个和第4个),可以使用 squeeze .


By the way, to remove singleton dimensions (3rd and 4th in your provided example), you can use squeeze.

这篇关于如何将零转换为NaN,然后​​取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆