如何在MATLAB中忽略NaN? [英] How to ignore NaNs in MATLAB?
问题描述
我正在寻找一种方法来忽略矩阵中的特定条目,以便随后在MATLAB中进行线性回归
I'm looking for a way to ignore specific entries in matrices for subsequent linear regression in MATLAB
我有两个矩阵:y =
I have two matricies: y =
9.3335 7.8105 5.8969 3.5928
23.1580 19.6043 15.3085 8.2010
40.1067 35.2643 28.9378 16.6753
56.4697 51.8224 44.5587 29.3674
70.7238 66.5842 58.8909 42.7623
83.0253 78.4561 71.1924 53.8532
和x =
300 300 300 300
400 400 400 400
500 500 500 500
600 600 600 600
700 700 700 700
800 800 800 800
我需要对y在20到80之间的点进行线性回归,因此我需要一种使过程完全自动化的方法.我尝试制作偏远的y值[及其对应的x值] NaN,但是在线性回归过程中,matlab在计算中包括了NaN,所以我得到了NaN输出.谁能建议一个忽略这些条目或完全忽略NaN的好方法? (请注意:y中的列通常具有不同的值组合,因此我无法消除整行).
I need to do linear regression on the points where y is between 20 and 80, so I need a way to fully automate the process. I tried making the outlying y values [and their corresponding x values] NaNs, but during linear regression, matlab included the NaNs in the calculations so I got NaN outputs. Can anyone suggest a good way to ignore those entries or to ignore NaNs completely calculations? (NOTE: the columns in y will often have different combinations of values, so I can't eliminate the whole row).
推荐答案
由于您分别在每一列上执行了回归,因此您可以简单地在具有有效y值的行中形成索引:
Since you perform your regression on each column separately, you can simply form an index into rows with the valid y-values:
nCols = size(x,2);
results = zeros(2,nCols);
validY = y>20 & y<80; %# a logical array the size of y with valid entries
nValid = sum(validY,1);
for c = 1:nCols
% results is [slope;intercept] in each column
results(:,c) = [x(validY(:,c),c),ones(nValid(c),1)]\y(validY(:,c),c);
end
这篇关于如何在MATLAB中忽略NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!