如果循环中任何Y为零,Matlab不会回归

时间:2019-02-23 13:18:24

标签: matlab regression linear-regression nan

我正在使用回归对大型nc文件(包含经度,纬度,时间和温度)执行线性回归。因此,对于每一个纬度和经度,温度都将回归30年(每年测量一次)。

在某些年份中,某些温度为0 K,在那些情况下,我希望环路不回归,因此最终平均斜率不包括这些温度。

下面是我代码的重要部分。

我没有收到错误,但是我是否包含y(y == 0)= NaN也没有任何区别,所以我认为可能有更好的方法。我了解到,回归会自动忽略这些,但事实并非如此。

% initialise time parameters
time_begin  = [1981, 1, 1, 0,0,0];
time_end    = [2010,12,31,23,0,0];
years       = (time_begin(1):time_end(1))';
nyears      = length(years);
% create storage and regress
TXx = randi(100, 288, 192, 30);
lat = rand(192, 1);
lon = rand(288, 1);
time = rand(30,1);
M = numel(lon);
N = numel(lat);
slope = zeros(M, N);
intercept = zeros(M, N);
T = numel(time);
x = ([ones(T, 1) years]);
% Regress each lat/lon location
for i = 1 : M
    for j = 1 : N
        % Get all time instances of each lat/lon location
        y = squeeze(TXx(i, j, :));
        y(y==0) = NaN;
        % Create regression problem and solve
        c = regress(y, x);
        intercept(i, j) = c(1);
        slope(i, j) = c(2);      
    end
end

1 个答案:

答案 0 :(得分:0)

NaN被忽略,但不是您想要的方式...单个数据点(而不是整个数据集)被忽略,因此仍然进行了回归。

您可以简单地使用if语句添加简单的支票,

for i = 1 : M
   for j = 1 : N
        % Get all time instances of each lat/lon location
        y = squeeze(TXx(i, j, :));
        if ~any(y==0)
            % Create regression problem and solve
            c = regress(y, x);
            intercept(i, j) = c(1);
            slope(i, j) = c(2);      
        end
    end
end