% This is a single input (x) fuzzy system with triangular input membership
% functions.  The parameter vector theta is used to define the value of the
% output.  range = [x1, x2] where x1 is the minimum input value and x2 is
% the max input.

function [y, mu] = fuzzy_sys(x, range, theta);

p = length(theta);
theta = theta(:);
x1 = range(1);
x2 = range(2);

% define the input membership function values
mu = zeros(p, 1);

% define the centers of the membership functions
d = (x2 - x1)/(p-1);
xc = (0:(p-1))*d + x1;

for i=1:p
  mu(i) = 1 - abs((x - xc(i))/d);
  if (mu(i) < 0) mu(i) = 0; end
end

% make sure that the membership fcns are properly defined at the extremes
if (x < x1) mu(1) = 1; end;
if (x > x2) mu(p) = 1; end;

mu = mu(:)/sum(mu);  % sum(mu) = 1 so this really should not do anything
y = mu'*theta;
