将所有NaN替换为零而不遍历整个矩阵?

问题描述:

我有一个想法,可以通过遍历每个NaN并使用isnan来替换矩阵中的所有NaN.但是,我怀疑这会使我的代码运行得比应该的慢.有人可以提供更好的建议吗?

I had an idea to replace all the NaNs in my matrix by looping through each one and using isnan. However, I suspect this will make my code run more slowly than it should. Can someone provide a better suggestion?

假设您的矩阵是:

A = 
     NaN   1       6
     3     5     NaN
     4     NaN     2

您可以找到NaN元素,并使用 isnan 将它们替换为零.像这样:

You can find the NaN elements and replace them with zero using isnan like this :

A(isnan(A)) = 0;

那么您的输出将是:

A =
     0     1     6
     3     5     0
     4     0     2