% CART Example

clear all;
close all;


%rng(1337); % fix random number generator

% generate sample features
% class 1
spread1_1 = randn([1000 1]);
spread1_2 = randn([1000 1]);
feat_class1(1:1000,1) = 0.1 + 0.2 * spread1_1 - 0.2 * spread1_2;
feat_class1(1:1000,2) = 0.1 + 0.2 * spread1_1 + 0.1 * spread1_2;
% class 2
spread2_1 = randn([1000 1]);
spread2_2 = 0.5 * randn([1000 1]);
feat_class2(1:1000,1) = 0.7 + 0.2 * spread2_1 - 0.2 * spread2_2;
feat_class2(1:1000,2) = 0.7 + 0.15 * spread2_1 + 0.15 * spread2_2;

% plot data
figure(1);
plot(feat_class1(:,1),feat_class1(:,2),'b*');
hold on;
plot(feat_class2(:,1),feat_class2(:,2),'r*');
xlim([0 1]);
ylim([0 1]);


% train one CART node
[x] = train_cart_leavenode(feat_class1,feat_class2);


% sample the decision of the CART node over the 2-D space
[X,Y] = meshgrid(0:0.001:1,0:0.001:1);
X = X .* (x(1));
Y = (1-Y) .* (x(2));
O = ones(size(X)) .* x(3);
Val = X + Y + O;
Val(Val > 0) = 1;
Val(Val < 1) = 0;

% numerically compute the decision Boundary
starti = size(Val,1);
endi = 1;
for i = 1:size(Val,1)
    for j =1:size(Val,2)-1
        if( Val(i,j+1) >0.5 && Val(i,j) < 0.5 ) || ( Val(i,j+1) < 0.5 && Val(i,j)  > 0.5 )
            boundaryY(i) = 1.0-(i/size(Val,1));
            boundaryX(i) = ((j +0.5)/size(Val,2));
            starti = min(i,starti);
            endi = max(i,endi);
            break;
        end
    end
end

% display the decision boundary
figure(1);
hold on;
plot(boundaryX(starti:endi),boundaryY(starti:endi),'k-');



