format long
format compact

vectorem=importdata("vectorem.csv");
vectorod=importdata("vectorod.csv");
vectorwind=importdata("vectorwind.csv");
vectorem=vectorem.data;
vectorod=vectorod.data;
vectorwind=vectorwind.data;
disp(size(vectorwind));
vectorem=vectorem([1:60 336:366],:);
vectorod=vectorod([1:60 336:366],:);
vectorwind=vectorwind([1:60 336:366],:);
disp(size(vectorwind));
emision_tot = reshape(vectorem,1,[]); % convert matrix to row vector
dod_tot = reshape(vectorod,1,[]); % convert matrix to row vector
winds_tot = reshape(vectorwind,1,[]); % convert matrix to row vector
windtf = 0.5; %(windtf) -> wind threshold value for filtering
indices0 = find(winds_tot<windtf);
winds_tot(indices0) = [];
dod_tot(indices0) = [];
emision_tot(indices0) = [];
mdl = fitlm(emision_tot,dod_tot);
intercept = mdl.Coefficients.Estimate(1);
 

nlim=1113;
wthreshold_robust = NaN(1,nlim);
c_robust = NaN(1,nlim);
for n = 1:nlim
    disp(n)
    emision = vectorem(:,n);
    winds = vectorwind(:,n);
    dod = vectorod(:,n);
    winds = winds.';
    emision = emision.';
    dod = dod.';
    dod = dod - intercept;
    indices = find(dod<0);
    winds(indices) = [];
    dod(indices)=[];
    indices2 = find(winds<windtf);
    winds(indices2) = [];
    dod(indices2)=[];
    if length(winds)>10
        fun = @(x,winds)(winds.^3)*x(1)+(winds.^2)*x(1)*x(2)-x(1)*(x(2).^2)*winds-x(1)*(x(2).^3);
        x0 = [0.5,0.5];
        lb = [0,0];
        ub = [Inf,Inf];
        % don't show infos from lsqcurvefit()
        options = optimset(@lsqcurvefit);
        options.Display = 'off';
        estParamsRobust = robustlsqcurvefit(fun, x0, winds, dod, lb, ub, [], options);
        wthreshold_robust(n) = estParamsRobust(2);
        c_robust(n) = estParamsRobust(1);
       
    end
    csvwrite('wthreshold_robust.csv',wthreshold_robust)
    csvwrite('c_robust.csv',c_robust)
end 
