% 1 antecedente 1 conseguente con Gaugen e MaxProd
% utile per osservare la forma delle regole in 3D
% Gu 3/03

xb = (0:0.1:10)';
len=max(size(xb));

a1=trap_mf(xb, [-0.1, 0, 2, 4]);
a2=trap_mf(xb, [2, 4, 5, 7]);
a3=trap_mf(xb, [5, 7, 10.2, 10.3]);


s=3;
c1=exts_mf(xb, [2, 8, s]) ;
c2=exts_mf(xb, [9, 3, s]) ;

figure
subplot(211),plot([a1,a2,a3]), title('antecedenti')
subplot(212),plot([c1, c2]), title('conseguenti')
figure

%Costruzione regole
%if x is a1 then y is c1
    [x,y] = meshgrid(a1, c1);    
    R1 = zeros(size(x));
    R1(find(x<=y)) = ones(size(find(x<=y)));
    R1(find(x>y)) = min(y(find(x>y)),x(find(x>y)));
      mesh(R1), title('if x is small then y is small - premi un tasto'), pause 
%if x is a3 then y is c1
    [x,y] = meshgrid(a3, c1);    
    R2 = zeros(size(x));
    R2(find(x<=y)) = ones(size(find(x<=y)));
    R2(find(x>y)) = min(y(find(x>y)),x(find(x>y)));
      mesh(R2), title('if x is large then y is small - premi un tasto'), pause
%if x is a2 then y is c2
    [x,y] = meshgrid(a2, c2);    
    R3 = zeros(size(x));
    R3(find(x<=y)) = ones(size(find(x<=y)));
    R3(find(x>y)) = min(y(find(x>y)),x(find(x>y)));
      mesh(R3), title('if x is medium then y is large - premi un tasto'), pause

%inferenza con antecedente "mobile"
out=[];
figure
for kk=1:0.25:9,
%ant=sglt(xb,kk);
ant=trap_mf(xb, [kk-2, kk-0.5, kk+0.5, kk+2]);
cons1=max_star(R1, ant, 'min');  
cons2=max_star(R2, ant, 'min');  
cons3=max_star(R3, ant, 'min');  
cons=min([cons1';cons2';cons3']); cons=cons';

subplot(2,2,1), plot(cons1), title('c1')
subplot(2,2,2), plot(cons2), title('c2')
subplot(2,2,3), plot(cons3), title('c3')
subplot(2,2,4), plot(cons), title(['ctot ' num2str(kk)])

out=[out, defuzzy(xb, cons, 1)];
pause(1)
end

