% Preprocessing für den Partitionsschätzer. Hier werden die Daten
% dimensionsweise auf das Intervall [0,1] gelegt. Nur die Extrema an beiden
% Rändern (in 1/100) werden aus dem Intervall gefiltert.

function [result] = random_forest_new(X_l, Y_l, X_t, Y_t, X_eval, Y_eval , max_number_tree)
    
    d=ceil(size(X_l,2)/2);
    number_tree_list=2.^(0:max_number_tree);
    
    minleaf_list=5;%2.^(0:6);
    number_minleaf=length(minleaf_list);
    
    forests=cell(d,1);
    errors=zeros(d,1);    
    best_ml=zeros(d,1); 
    treenumber=zeros(d,1); 
    
    Dummy_forests=cell(number_minleaf,1);
    Dummy_errors=zeros(number_minleaf,1);      
    Dummy_treenumber=zeros(number_minleaf,1);  
    options = statset('UseParallel','always');
    for dim=1:d

        for ml=1:number_minleaf

        Dummy_forests{ml} = TreeBagger(number_tree_list(max_number_tree+1),X_l,Y_l,'Method','regression','NVARTOSAMPLE',dim,'MinLeaf',minleaf_list(ml),'Options',options);
        
        Dummy_err=error(Dummy_forests{ml},X_t,Y_t,'trees',number_tree_list);
        
        [Dummy_errors(ml) Dummy_treenumber(ml)]=min(Dummy_err);

        end

        [errors(dim) best_ml(dim)]=min(Dummy_errors);
        
        forests{dim}=Dummy_forests{best_ml(dim)};
        treenumber(dim)=Dummy_treenumber(best_ml(dim));

    end
        
    
    [~, best_dim]=min(errors);
    
    Y_calc=predict(forests{best_dim},X_eval,'trees',1:2^(treenumber(best_dim)-1));

    result.mse=mean((Y_calc-Y_eval).^2);
    result.res=Y_calc-Y_eval;
    result.param=[2^(treenumber(best_dim)-1) minleaf_list(best_ml(dim)) best_dim ];
    
    
end

