You are on page 1of 48

FUZZY LOGIC - AN INTRODUCTION

PART 1
WHERE DID FUZZY LOGIC COME FROM?
The concept of Fuzzy Logic (FL) was conceived at the beginning of the 70s by Lotfi
Zadeh, a professor at the University of California at Berkley, and presented not as a
control methodology, but as a way of processing data by allowing partial set membership
rather than crisp set membership or non-membership. This approach to set theory was not
applied to control systems until the 70's due to insufficient small-computer capability
prior to that time. Professor Zadeh reasoned that people do not require precise, numerical
information input, and yet they are capable of highly adaptive control. If feedback
controllers could be programmed to accept noisy, imprecise input, they would be much
more effective and perhaps easier to implement.
WHAT IS FUZZY LOGIC?
In this context, FL is a problem-solving control system methodology that lends itself to
implementation in systems ranging from simple, small, embedded micro-controllers to
large, networked, multi-channel PC or workstation-based data acquisition and control
systems. It can be implemented in hardware, software, or a combination of both. FL
provides a simple way to arrive at a definite conclusion based upon vague,
ambiguous, imprecise, noisy, or missing input information. FL's approach to control
problems mimics how a person would make decisions, only much faster.
HOW IS FL DIFFERENT FROM CONVENTIONAL CONTROL METHODS?
FL incorporates a simple, rule-based IF X AND Y THEN Z approach to a solving
control problem rather than attempting to model a system mathematically. The FL model
is empirically-based, relying on an operator's experience rather than their technical
understanding of the system. For example, rather than dealing with temperature control in
terms such as "SP =500F", "T <1000F", or "210C <TEMP <220C", terms like "IF
(process is too cool) AND (process is getting colder) THEN (add heat to the process)" or
"IF (process is too hot) AND (process is heating rapidly) THEN (cool the process
quickly)" are used. These terms are imprecise and yet very descriptive of what must
actually happen. Consider what you do in the shower if the temperature is too cold: you
will make the water comfortable very quickly with little trouble. FL is capable of
mimicking this type of behavior but at very high rate.
HOW DOES FL WORK?
FL requires some numerical parameters in order to operate such as what is considered
significant error and significant rate-of-change-of-error, but exact values of these
numbers are usually not critical unless very responsive performance is required in which
case empirical tuning would determine them. For example, a simple temperature control

system could use a single temperature feedback sensor whose data is subtracted from the
command signal to compute "error" and then time-differentiated to yield the error slope
or rate-of-change-of-error, hereafter called "error-dot". Error might have units of degs F
and a small error considered to be 2F while a large error is 5F. The "error-dot" might then
have units of degs/min with a small error-dot being 5F/min and a large one being
15F/min. These values don't have to be symmetrical and can be "tweaked" once the
system is operating in order to optimize performance. Generally, FL is so forgiving that
the system will probably work the first time without any tweaking.

FUZZY LOGIC - AN INTRODUCTION


PART 2
WHY USE FL?
FL offers several unique features that make it a particularly good choice for many control
problems.
1) It is inherently robust since it does not require precise, noise-free inputs and can
be programmed to fail safely if a feedback sensor quits or is destroyed. The output
control is a smooth control function despite a wide range of input variations.
2) Since the FL controller processes user-defined rules governing the target control
system, it can be modified and tweaked easily to improve or drastically alter system
performance. New sensors can easily be incorporated into the system simply by
generating appropriate governing rules.
3) FL is not limited to a few feedback inputs and one or two control outputs, nor is it
necessary to measure or compute rate-of-change parameters in order for it to be
implemented. Any sensor data that provides some indication of a system's actions
and reactions is sufficient. This allows the sensors to be inexpensive and imprecise thus
keeping the overall system cost and complexity low.
4) Because of the rule-based operation, any reasonable number of inputs can be
processed (1-8 or more) and numerous outputs (1-4 or more) generated.
5) FL can control nonlinear systems that would be difficult or impossible to model
mathematically.
HOW IS FL USED?
1) Define the control objectives and criteria: What am I trying to control? What do I
have to do to control the system? What kind of response do I need? What are the possible
(probable) system failure modes?
2) Determine the input and output relationships and choose a minimum number of
variables for input to the FL engine (typically error and rate-of-change-of-error).
3) Using the rule-based structure of FL, break the control problem down into a series
of IF X AND Y THEN Z rules that define the desired system output response for given

system input conditions. The number and complexity of rules depends on the number of
input parameters that are to be processed and the number fuzzy variables associated with
each parameter. If possible, use at least one variable and its time derivative. Although it is
possible to use a single, instantaneous error parameter without knowing its rate of
change, this cripples the system's ability to minimize overshoot for a step inputs.
4) Create FL membership functions that define the meaning (values) of
Input/Output terms used in the rules.
5) Create the necessary pre- and post-processing FL routines if implementing in S/W,
otherwise program the rules into the FL H/W engine.
6) Test the system, evaluate the results, tune the rules and membership functions, and
retest until satisfactory results are obtained.
LINGUISTIC VARIABLES
In 1973, Professor Lotfi Zadeh proposed the concept of linguistic or "fuzzy" variables.
Think of them as linguistic objects or words, rather than numbers. The sensor input is a
noun, e.g. "temperature", "displacement", "velocity", "flow", "pressure", etc. Since error
is just the difference, it can be thought of the same way. The fuzzy variables themselves
are adjectives that modify the variable (e.g. "large positive" error, "small positive"
error,"zero" error, "small negative" error, and "large negative" error). As a minimum, one
could simply have "positive", "zero", and "negative" variables for each of the parameters.
Additional ranges such as "very large" and "very small" could also be added to extend the
responsiveness to exceptional or very nonlinear conditions, but aren't necessary in a basic
system.

FUZZY LOGIC - AN INTRODUCTION


PART 3
THE RULE MATRIX

0

0 _
_
0

0 _

In the last article the concept of linguistic variables was presented. The fuzzy
0 0 parameters of error (command-feedback) and error-dot (rate-of-change-oferror) were modified by the adjectives "negative", "zero", and "positive". To
picture this, imagine the simplest practical implementation, a 3-by-3 matrix.
_ _
The columns represent "negative error", "zero error", and "positive error"
_ _
inputs from left to right. The rows represent "negative", "zero", and "positive"
"error-dot" input from top to bottom. This planar construct is called a rule
_ _
matrix. It has two input conditions, "error" and "error-dot", and one output
response conclusion (at the intersection of each row and column). In this case there are
nine possible logical product (AND) output response conclusions.
Although not absolutely necessary, rule matrices usually have an odd number of rows and
columns to accommodate a "zero" center row and column region. This may not be needed
as long as the functions on either side of the center overlap somewhat and continuous
dithering of the output is acceptable since the "zero" regions correspond to "no change"

output responses the lack of this region will cause the system to continually hunt for
"zero". It is also possible to have a different number of rows than columns. This occurs
when numerous degrees of inputs are needed. The maximum number of possible rules is
simply the product of the number of rows and columns, but definition of all of these rules
may not be necessary since some input conditions may never occur in practical operation.
The primary objective of this construct is to map out the universe of possible inputs
while keeping the system sufficiently under control.
STARTING THE PROCESS
The first step in implementing FL is to decide exactly what is to be controlled and how.
For example, suppose we want to design a simple proportional temperature controller
with an electric heating element and a variable-speed cooling fan. A positive signal output
calls for 0-100 percent heat while a negative signal output calls for 0-100 percent cooling.
Control is achieved through proper balance and control of these two active devices.

Figure 1 - A simple block diagram of the control system.


It is necessary to establish a meaningful system for representing the linguistic variables in
the matrix.
Define the minimum number of possible input product combinations and corresponding
output response conclusions using these terms. For a three-by-three matrix with heating
and cooling output responses, all nine rules will need to be defined. The conclusions to
the rules with the linguistic variables associated with the output response for each rule are
transferred to the matrix.
WHAT IS BEING CONTROLLED AND HOW:

Figure 2 - Typical control system response


Figure 2 shows what command and error look like in a typical control system relative to
the command setpoint as the system hunts for stability.
Linguistic rules describing the control system consist of two parts; an antecedent block
(between the IF and THEN) and a consequent block (following THEN). Depending on
the system, it may not be necessary to evaluate every possible input combination (for
5-by-5 & up matrices) since some may rarely or never occur. By making this type of
evaluation, usually done by an experienced operator, fewer rules can be evaluated,
thus simplifying the processing logic and perhaps even improving the FL system
performance.

Figures 3 & 4 - The rule structure.

After transferring the conclusions from rules to the matrix there is a noticeable symmetry
to the matrix. This suggests (but doesn't guarantee) a reasonably well-behaved (linear)
system. This implementation may prove to be too simplistic for some control problems,
however it does illustrate the process. Additional degrees of error and error-dot may be
included if the desired system response calls for this. This will increase the rulebase size
and complexity but may also increase the quality of the control. Figure 4 shows the rule
matrix derived from the previous rules.
SUMMARY
Linguistic variables are used to represent an FL system's operating parameters. The rule
matrix is a simple graphical tool for mapping the FL control system rules. It
accommodates two input variables and expresses their logical product (AND) as one
output response variable. To use, define the system using plain-English rules based upon
the inputs, decide appropriate output response conclusions, and load these into the rule
matrix.

FUZZY LOGIC - AN INTRODUCTION


PART 4
MEMBERSHIP FUNCTIONS
In the last article, the rule matrix was introduced and used. The next logical question is
how to apply the rules. This leads into the next concept, the membership function.
The membership function is a graphical representation of the magnitude of
participation of each input. It associates a weighting with each of the inputs that are
processed, define functional overlap between inputs, and ultimately determines an
output response. The rules use the input membership values as weighting factors to
determine their influence on the fuzzy output sets of the final output conclusion. Once the
functions are inferred, scaled, and combined, they are defuzzified into a crisp output
which drives the system. There are different membership functions associated with each
input and output response. Some features to note are:
SHAPE - triangular is common, but bell, trapezoidal, haversine and, exponential have
been used. More complex functions are possible but require greater computing overhead
to implement. HEIGHT or magnitude (usually normalized to 1) WIDTH (of the base of
function), SHOULDERING (locks height at maximum if an outer function. Shouldered
functions evaluate as 1.0 past their center) CENTER points (center of the member
function shape) OVERLAP (N&Z, Z&P, typically about 50% of width but can be less).

Figure 5 - The features of a membership function


Figure 5 illustrates the features of the triangular membership function which is used in
this example because of its mathematical simplicity. Other shapes can be used but the
triangular shape lends itself to this illustration.
The degree of membership (DOM) is determined by plugging the selected input
parameter (error or error-dot) into the horizontal axis and projecting vertically to the
upper boundary of the membership function(s).
ERROR & ERROR-DOT FUNCTION MEMBERSHIP
The degree of membership for an "error" of -1.0 projects up to the middle of the
overlapping part of the "negative" and "zero" function so the result is "negative"
membership = 0.5 and "zero" membership = 0.5. Only rules associated with "negative" &
"zero" error will actually apply to the output response. This selects only the left and
middle columns of the rule matrix.
For an "error-dot" of +2.5, a "zero" and "positive" membership of 0.5 is indicated. This
selects the middle and bottom rows of the rule matrix. By overlaying the two regions of
the rule matrix, it can be seen that only the rules in the 2-by-2 square in the lower left
corner (rules 4,5,7,8) of the rules matrix will generate non-zero output conclusions. The
others have a zero weighting due to the logical AND in the rules.

FUZZY LOGIC - AN INTRODUCTION


PART 5
PUTTING IT ALL TOGETHER
As inputs are received by the system, the rulebase is evaluated. The antecedent (IF X
AND Y) blocks test the inputs and produce conclusions. The consequent (THEN Z)
blocks of some rules are satisfied while others are not. The conclusions are combined to
form logical sums. These conclusions feed into the inference process where each
response output member function's firing strength (0 to 1) is determined.

Figure 7 - Degree of membership for the error and error-dot functions in the current
example


0
0
0

0 0
C
C
4
C 7

H
5
C8

0
H
H
H

Data summary from previous illustrations:


INPUT DEGREE OF MEMBERSHIP
"error" = -1.0: "negative" = 0.5 and "zero" = 0.5
"error-dot" = +2.5: "zero" = 0.5 and "positive" = 0.5

ANTECEDENT & CONSEQUENT BLOCKS (e = error, er = error-dot or errorrate)


Now referring back to the rules, plug in the membership function weights from above.
"Error" selects rules 1,2,4,5,7,8 while "error-dot" selects rules 4 through 9. "Error" and
"error-dot" for all rules are combined to a logical product (LP or AND, that is the
minimum of either term). Of the nine rules selected, only four (rules 4,5,7,8) fire or have
non-zero results. This leaves fuzzy output response magnitudes for only "Cooling" and
"No_Change" which must be inferred, combined, and defuzzified to return the actual
crisp output. In the rule list below, the following ddefinitions apply: (e)=error, (er)=errordot.
1. If (e < 0) AND (er < 0) then Cool 0.5 & 0.0 = 0.0
2. If (e = 0) AND (er < 0) then Heat 0.5 & 0.0 = 0.0
3. If (e > 0) AND (er < 0) then Heat 0.0 & 0.0 = 0.0
4. If (e < 0) AND (er = 0) then Cool 0.5 & 0.5 = 0.5
5. If (e = 0) AND (er = 0) then No_Chng 0.5 & 0.5 = 0.5
6. If (e > 0) AND (er = 0) then Heat 0.0 & 0.5 = 0.0
7. If (e < 0) AND (er > 0) then Cool 0.5 & 0.5 = 0.5
8. If (e = 0) AND (er > 0) then Cool 0.5 & 0.5 = 0.5
9. If (e > 0) AND (er > 0) then Heat 0.0 & 0.5 = 0.0

FUZZY LOGIC - AN INTRODUCTION


PART 6
INFERENCING
The last step completed in the example in the last article was to determine the firing
strength of each rule. It turned out that rules 4, 5, 7, and 8 each fired at 50% or 0.5 while
rules 1, 2, 3, 6, and 9 did not fire at all (0% or 0.0). The logical products for each rule
must be combined or inferred (max-min'd, max-dot'd, averaged, root-sum-squared, etc.)
before being passed on to the defuzzification process for crisp output generation. Several
inference methods exist.
The MAX-MIN method tests the magnitudes of each rule and selects the highest one. The
horizontal coordinate of the "fuzzy centroid" of the area under that function is taken as
the output. This method does not combine the effects of all applicable rules but does
produce a continuous output function and is easy to implement.
The MAX-DOT or MAX-PRODUCT method scales each member function to fit under
its respective peak value and takes the horizontal coordinate of the "fuzzy" centroid of the
composite area under the function(s) as the output. Essentially, the member function(s)
are shrunk so that their peak equals the magnitude of their respective function

("negative", "zero", and "positive"). This method combines the influence of all active
rules and produces a smooth, continuous output.
The AVERAGING method is another approach that works but fails to give increased
weighting to more rule votes per output member function. For example, if three
"negative" rules fire, but only one "zero" rule does, averaging will not reflect this
difference since both averages will equal 0.5. Each function is clipped at the average and
the "fuzzy" centroid of the composite area is computed.
The ROOT-SUM-SQUARE (RSS) method combines the effects of all applicable rules,
scales the functions at their respective magnitudes, and computes the "fuzzy" centroid of
the composite area. This method is more complicated mathematically than other methods,
but was selected for this example since it seemed to give the best weighted influence to
all firing rules.
DEFUZZIFICATION - GETTING BACK TO CRISP NUMBERS
The RSS method was chosen to include all contributing rules since there are so few
member functions associated with the inputs and outputs. For the ongoing example, an
error of -1.0 and an error-dot of +2.5 selects regions of the "negative" and "zero" output
membership functions. The respective output membership function strengths (range: 0-1)
from the possible rules (R1-R9) are:
Neg _ Strength R12 R 42 R72 R82 0 2 0.5 2 0.5 2 0.5 2 0.866
Zero _ Strength R52 0.5 2 0.5
Pos _ Strength R 22 R32 R62 R92 0 2 0 2 0 2 0 2 0

A "FUZZY CENTROID" ALGORITHM


The defuzzification of the data into a crisp output is accomplished by combining the
results of the inference process and then computing the "fuzzy centroid" of the area.
The weighted strengths of each output member function are multiplied by their respective
output membership function center points and summed. Finally, this area is divided by
the sum of the weighted member function strengths and the result is taken as the crisp
output. One feature to note is that since the zero center is at zero, any zero strength will
automatically compute to zero. If the center of the zero function happened to be offset
from zero (which is likely in a real system where heating and cooling effects are not
perfectly equal), then this factor would have an influence.
Neg _ Center Neg _ Strength Zero _ Center Zero _ Strength Pos _ Center Pos _ Strength
Neg _ Strength Zero _ Strength Pos _ Strength
Output
100 0.866 0 0.5 100 0
63.4%
0.866 0.5 0

Figure 8 - The horizontal coordinate of the centeriod is taken as the crisp output
The horizontal coordinate of the centroid of the area marked in Figure 8 is taken as the
normalized, crisp output. This value of -63.4% (63.4% Cooling) seems logical since the
particular input conditions (Error=-1, Error-dot=+2.5) indicate that the feedback has
exceeded the command and is still increasing therefore cooling is the expected and
required system response.
TUNING AND SYSTEM ENHANCEMENT
Tuning the system can be done by changing the rule antecedents or conclusions, changing
the centers of the input and/or output membership functions, or adding additional degrees
to the input and/or output functions such as "low", "medium", and "high" levels of
"error", "error-dot", and output response. These new levels would generate additional
rules and membership functions which would overlap with adjacent functions forming
longer "mountain ranges" of functions and responses. The techniques for doing this
systematically are a subject unto itself.
CONCLUSION
Fuzzy Logic provides a completely different, unorthodox way to approach a control
problem. This method focuses on what the system should do rather than trying to
understand how it works. One can concentrate on solving the problem rather than trying
to model the system mathematically, if that is even possible. This almost invariably leads
to quicker, cheaper solutions. Once understood, this technology is not difficult to apply
and the results are usually quite surprising and pleasing.

FUZZY TOOLBOX
Matlab is used for implementing fuzzy relations and sets. The Matlab toolbox and
simulink helps the user to view the real time simulations and how the fuzzy logic
works and can be applied for different fields.
The inbuilt fuzzy logic toolbox will pop up when you type fuzzy at the command
prompt. This toolbox has been developed in the Matlab using some predefined
basic functions using the Matlabs GUI (Graphical User Interface). We can shape
the toolbox as required with user defined functions. This project deals a particular
application. When the user possesses the rough idea of what should be the value
of input1 and Input2, the toolbox will calculate the value of output based on those
values.
Overview:
The toolbox designed may not be as good as the inbuilt fuzzy tipper, but
this is an attempt to get the best results using some programming fundamentals
and user defined functions. The toolbox is names as fuzzytool1. The toolbox
provides user to define the range of the input membership functions and the
output membership functions. This toolbox has two inputs and a single output.
The rules used are defined in ft3. In the rules window the input and output
membership functions are displayed. The membership function used here is
triangle. In most of the applications the triangle membership function is well
suited for the purpose and provides satisfactory results.
The user can define the input1 and input2 values and check the output
value and membership function from the rule window. This method is universally
accepted as the best one and proved to be giving consistent results. The user can
check the value and membership function for both AND & OR methods. The
AND method works as min function and OR works as max function. The clipping
method is used in the design process for obtaining output.

The Fuzzy tool window:

Fig. 1

The Fig. 1 shows the, main window when fuzzy tool box is started by typing
Fuzzytool1 at the Matlab prompt (>>). It displays the type of membership functions
used for the two inputs viz. Input1 & Input2 which is triangular in both the cases.
Moreover the Type of membership function used for representing the output is also
triangular.
If we click on the axes background of Input1, Input2, or Output we can open the window
showing their characteristics membership functions and a window showing IF -Then
Rules for FIS Mamdani.

The AND Method uses Min. Function, OR method uses Max. Function, implication uses
Min. Function and the type of Defuzzification used is cantroid.

By clicking on the back ground of axes labeled input1 or input2 we can open a window
ft2 that looks like this:

Fig. 2
ft2 basically shows Membership functions of inputs and output. In both the cases, the
type of membership function used is Triangular that can be seen in the MF Plots axis by
clicking on input or output push buttons at the top left of the ft2 window (Fig.2).

The two panels in the same window display the properties of the variables selected.

Fig. 3
We can change the value of the parameters used to draw any of the three triangles in the
corresponding edit boxes. When we press input or output buttons the changes can viewed
in the display window (Fig. 4).

After changing value in any of the edit boxes press input buttons or output button, the
plot will change itself accordingly as shown in Fig. 4

Fig. 4
We can see in Fig. 4 that after changing the value of the parameters in the second edit box
from 7.5 to 8 directly into the edit box the green colored triangle changes accordingly. We
need to press any of the push buttons labeled input1, input2, and output on the top
left of the window before toolbox can implement any change in the plot.
The Show Rules button when pressed opens a window shown in Fig. 5 that contains the
IF-THEN rules and the close button closes the window.

Rules Window:

Fig. 5
The Fig. 5 shows the rules window that display all the rules used by the Fuzzy Inferences
Set to come to the desired output. It provides options for Input1 and Input2 and we can
set the output based on the two inputs using pop-up menus. It also provides options to
choose from AND/OR methods using Radio buttons. We can select only one option from
the two conjunctions.
The bottom of the window in Fig. 5 shows FIS Name and a close button that closes the
window and we return back to the FIS Mamdani window.

The menu items can be used to switch to other windows in the whole application.
The File menu provides options like New FIS, Exit and the Edit provides options like
Rules, Membership functions, etc. Last menu item View provides options like View
Rules and surface. For example, if we select Rules in the view menu, the toolbox opens
f4 window that looks like what is shown in Fig. 6

The f4 window:

Fig. 6
Fig. 6 shows the main output window where we can view analyze and verify the input
and output plots. There are three inputs under the label input1 & input2 and three
outputs under the label output. The fourth plot under the output label provides the
defuzzified output plot. This plot is used to calculate the final value of output variable.
We have the same items in the menu as in previous windows and one inputs edit box
where we can select and change input variables. The default value of input1 is 4 and for
input2 it is 7. We can anytime change these values as per our rules.
When we press the Plot pushbutton at the bottom of the window, we can see the plots of
the membership functions of the two inputs and the output. The last plot displays the
defuzzified output from where we can obtain the value of output.

The close button closes all the windows.


The Fig. 7 makes everything clear.

Fig. 7
If we want to switch back to the main window i.e. Fuzzytool1 window (Fig. 1) then we
can select New FIS option from the file menu of this window or we can select Exit to
close all the windows and return to Matlab.

Important Conclusions:
This Fuzzy tool is developed using the IDE feature of the MATLAB version 7.0. It
demonstrates some basic features of a Fuzzy tool box and triangular Membership
function is being used to imitate the Fuzzy tipper included in the Matlab Software. It can
be used for two different inputs to obtain one output. It provides options for two Fuzzy
Inference Systems viz. Mamdani and Sugeno that can be selected from File menu of any
windows of the application.
Shortcomings: This Tool requires that the user must have the knowledge of how to plot
the membership functions, like Triangular MF for Input1 or output, when to select Rules
option from the edit menu and when press close buttons without which he may get the
erroneous results or he may close the application before he can see the output plots.
Finally, the Fuzzy tool provides the user to work with the basic ideas of the fuzzy
inference systems.
FIS-INTROUCTION
Create a Fuzzy Inference System Using Commands in M-file
Step 1: In Matlab main console window, select FileNewM File. The M File
Editor window is pop-up.
Step 2: Type the following code into your M File Editor and save it as M1.mat.
Notice that the same code can be obtained by Select FileOpen
MFile1.mat in M File Editor Window.
a = newfis('fis1.fis'); %create a new FIS file in "work" folder
%add and input variable 'x' into the FIS
a = addvar(a, 'input', 'x', [2 9]);
%remove the 3 MFs created by default when we add an input variable
a = rmmf(a, 'input', 1, 'mf1', 1);
a = rmmf(a, 'input', 1, 'mf2', 1);

a = rmmf(a, 'input', 1, 'mf3', 1);


%add 2 MFs into the variable x
a = addmf(a, 'input', 1, 'A1', 'trimf', [2 5 8]);
a = addmf(a, 'input', 1, 'A2', 'trimf', [3 6 9]);
%add and input variable 'x' into the FIS
a = addvar(a, 'input', 'y', [4 11]);
%remove the 3 MFs created by default when we add an input variable
a = rmmf(a, 'input', 2, 'mf1', 1);
a = rmmf(a, 'input', 2, 'mf2', 1);
a = rmmf(a, 'input', 2, 'mf3', 1);
%add 2 MFs into the variable y
a = addmf(a, 'input', 2, 'B1', 'trimf', [5 8 11]);
a = addmf(a, 'input', 2, 'B2', 'trimf', [4 7 10]);
%add and output variable 'y' into the FIS
a = addvar(a, 'output', 'z', [1 9]);
%remove the 3 MFs created by default when we add an output variable
a = rmmf(a, 'output', 1, 'mf1', 1);
a = rmmf(a, 'output', 1, 'mf2', 1);
a = rmmf(a, 'output', 1, 'mf3', 1);
%add 2 MFs into the variable x
a = addmf(a, 'output', 1, 'C1', 'trimf', [1 4 7]);
a = addmf(a, 'output', 1, 'C2', 'trimf', [3 6 9]);
%1 rule is defined and added into FIS
rule = [1 1 1 1 1];
a = addrule(a, rule);
%The 1st '1' is mean that the 1st MF of 1st input variable will be use in this rule, in this
case, A1 will be use
%You can put '2' if you want to use 2nd MF of 1st input variable, use '0' if you do not
wise the rule involve with 1st input variable
%The 2nd '1' is mean that the 1st MF of 2nd input variable will be use in this rule, in this
case, B1 will be use
%You can put '2' if you want to use 2nd MF of 1st input variable, use '0' if you do not
wise the rule involve with 2nd input variable
%The 3rd '1' is mean that the 1st MF of output variable will be use in this rule, in this
case, C1 will be use

%You can put '2' if you want to use 2nd MF of output variable
%The 4th '1' is mean that this rule is create and Enable, use '0' to to create the rule but
Disable it.
%The 5th '1' is mean that the relationship between MF of 1st input variable and MF 2nd
input variable is "AND"
%Use '2' is you want it to be "OR"
%Conclusion, this will add a fule, if x is A1 and y is B1 Then z is C1
writefis(a, 'fis1.fis');
disp('A new FIS is created and save as \work\fis1.fis');
disp('Type "Fuzzy fis1.fis" in console window to see the new FIS created');
disp('End of the program mfile1.m');
To View the FIS created
This can be done by Type Fuzzy fis1 (the .fis in behind can be ignore).
The FIS Editor will be shown as in Figure 1 below.

Figure 1

You can change the setting of the FIS here, such as change the Defuzzification to
MOM rather using COA (See Figure 1).
Double Click on the part show the MFs of x in order to see (and change) the detail
information of MFs of input x created in the code as shown in Figure 2.
Same steps can be done to for variables y and z.

Figure 2

Select EditRule to view and edit the rule added in the code above. The
Rule Editor is shown in Figure 3 below.

Figure 3
Select ViewSurface to see the decision surface base on the rule(s) created.
The Surface Viewer is shown in Figure 4 below.

Figure 4

Select ViewRules to see how to inference system work in order to product


and output based on the inputs given. We can use to mouse to drag and place the
red lines in order to change the inputs and to see the new output as well. See
Figure 5 for detail

As a conclusion, to create a new FIS


via 5command is slow. The FIS Edit actually
Figure
can be use to create or modify FIS in very short time compare to command coding
method.

Exercise: Modify the code in MFile1.m above so that it can take three rules as
below.
R1: If x is A1 and y is B1 then z is C1
R2: If x is A2 and y is B2 then z is C2
R3: If x is A1 or y is B2 then z is C2
Solution:
Modify only one line in to code
rule = [1 1 1 1 1; 2 2 2 1 1; 1 2 2 1 2];
You can use FIS editor to check your answer, notice that the surface viewer will not
be the same as before since rules are added.
Another way to see the result is typing command in console windows.
F = readfis(fis1.fis) %Press enter key
%information of the FIS will be show.
Showrule(F);
%the rule of this FIS will be show.
Create common FIS use for Control Systems Using FIS Editor.
Step 1: Type Fuzzy in the Matlab console window. The FIS edit will be show.

Step 2: Select EditAdd VariableInput to add the second input variable.


Step 3: Highlight on input1, change the name of input1 to E (error), as shown in
picture below. The rest of information is no change. See Figure 6 for detail

P
R
Q

Name of variable is E

Figure 6
Step 4: Repeat step 3 for input2 become DE (change of error) and the output
become U (control signal).
Step 5: Double click on the picture of MFs for variable E, as shown in area P in
Figure 6, in order to shown the MFs of variable E. By default when a variable is
added, 3 MFs will be automatically. See Figure 7.
Step 6: It will be easy for us to delete all the default MFs, this can be done by select
EditRemove All MFs as shown in Figure 7. After this, no more MFs for input
variable E.

Figure 7
Step 7: Now we plan to add 7 MFs to input variable E, this can be done by select
EditAdd MFs. After select this, another dialog box is pop up as shown in
Figure 8. Select Type MFs as gaussmf and number of MFs is 7. See Figure 8 for
detail.

Figure 8
Step 8: Select OK by click on the OK button. Now 7 MFs have been add into
input variable E as shown in Figure 9

Figure 9

Step 9: Highlight the mf1 as shown in Figure 9. Change the name of mf1 to NB as
shown in area X
Step 10: Repeat Step 9 for mf2 to mf7, to change their names become NM, NS, ZR,
PS, PM and PB.
Step 11: Change the range of the variable to [-1 1] as shown in area Y.
Step 12: Repeat Step 5 to Step 11 but for input variable DE.
Step 13: Repeat Step 5 to Step 12 but for output variable U.
Step 14: Select EditRule, the rule editor windows is shown as Figure 10.

Figure 10
Figure 10
Step 15: Add the 1st rule into rule editor base on what we have learn in Module 3.
E.g the 1st rule is: If E is NB and DE is NB then U is NB
Step 16: Repeat Step 16 to create 2nd until 49th rules.
Step 17: Now we can select ViewSurfaces to see the decision surface of this
general fuzzy logic control, or select ViewRules to see the inference process
and the output when inputs are given.
Step 18: Select FileExportDisk to save the FIS created into disk. Do type
a file name when you are being as to do so. See Figure 11 for detail.

Figure 11
Step 19: If you want the FIS to load into memory, select
FileExportWorkspace Do type a workspace name when you are being as to
do so. See Figure 11 for detail.
Step 20: Test your FIS created in console windows of Matlab, type the commands
below.
>> f = readfis('fis2.fis') %Command that you type, read the fis into pointer f
f = %information show by matlab
name: 'fis2'
type: 'mamdani'
andMethod: 'min'
orMethod: 'max'
defuzzMethod: 'centroid'
impMethod: 'min'
aggMethod: 'max'
input: [1x2 struct]
output: [1x1 struct]
rule: [1x49 struct]

>> evalfis([0.2 0.9], f) %command that you type, meaning if E = 0.2 and DE = 0.9, what is U?
ans =

%answer calculated by Matlab, U = 0.7530


0.7530

A Fuzzy Logic Controller for Water bath Temperature Control


Problem statement: In this demonstration, we shall design a fuzzy logic controller for the
temperature control of a water bath. The plant to be controlled is described by:
b(T )u (k )
(1 a (T ))Y0
1 exp(0.5 y (k ) )
(1 exp(T ))
Where a (T ) exp(T ) and b(T )
. The parameters of the plant
y (k 1) a (T ) y (k )

o
, 8.7 x10 3 , 40 and Y0 25 C . The plant input u(k) is

are set as 1x10


limited to between 0 and 5 volts. The sampling period, T, is set as 25 seconds. The goal is
to design a fuzzy controller what will control the water temperature to follow a reference
profile as closely as possible. This reference profile is 35 o C for 0 t 40 minutes,
50 o C for 40 t 80 minutes, 65 o C for 80 t 120 minutes and 80 o C for
120 t 180 minutes.
4

The input variables for this controller are chosen as e(k), de(k) where e(k) is the
performance error indicating the error between the desire output and the actually output.
The de(k) is the change of the error. The output of the controller is the voltage that
limited to between 0 to 5 volts.
The source code is shown as below, where we use the FIS (fis2.fis) designed in previous
section in this application. Notice that the same source code can be found in
\work\mfile2.m
% =======================
%
Filename : mfile2
% =======================
clear; %clear the memory of matlab
echo on; %to show result of every command
clc;%to clear the matlab console screen
%
%
%

===========================================================
A Fuzzy Controller for the Water Bath Temperature Control
===========================================================

% ====================================================================
% Problem Statement: To design a fuzzy controller for
% the temperature control of a water bath.
% The equations and the parameters of the plant
% to be controlled are described in Module 3.

% The goal is to design a fuzzy controller that will


% control the water temperature to follow a
% reference profile as close as possible.
%
% =========================================================
% Notice that the FIS used is desgined using FIS editor.
% =========================================================
%
%
%

===============
Test program
===============

pause % Hit any key to begin this program.


% Read the FIS file .
f = readfis('fis2.fis');
pause % Hit any key to define the plant parameters.
T = 25;
p = 1*10^(-4);
q = 8.7*10^(-3);
r = 40.0;
yo = 25;
y(1) = yo;
a = exp(-p*T);
b=(q/p)*(1-exp(-p*T));
pause % Hit any key to define the reference output.
for k = 1:180
if (k <= 40)
ref(k) = 35;
elseif (k > 40 & k <= 80)
ref(k) = 50;
elseif (k > 80 & k <= 120)
ref(k) = 65;
elseif (k > 120)
ref(k) = 80;
end;
end;
pause % Hit any key to define the gain constanT.
GE = 1/15;
GDE = 1/15;
GU = 80;
pause % Hit any key to test this fuzzy controller.
for k = 1:179
e(k)=(ref(k)-y(k)); %error
ef(k)=e(k)*GE; %scaled of error
if k == 1
de(k) = 0; %change of error
else
de(k) = e(k)-e(k-1);
end;

def(k) = de(k)*GDE; %scaled of change of error


uf(k) = evalfis([ef(k) def(k)],f); %obtain the control signal using FIS base on the error and change of
error
u(k) = uf(k)*GU; %scale it back
%because in real world the control signal shall be in between 0 to 5 volt
if (u(k)>=5)
u(k)=5;
elseif (u(k)<=0)
u(k)=0;
end;
%put all the information including the new control signal into the plant
y(k+1)=a*y(k)+b/(1+exp(0.5*y(k)-r))*u(k)+(1-a)*yo;
end;
% ...end of testing.
pause % Hit any key to plot the plant input and output, and the reference output.
hold on;
grid;
plot(y(1:180),'.b');
plot(ref(1:180),'-r');
plot(u(1:179),'g');
xlabel('Sampling Time Step KT T=25 seconds');
ylabel('Temperature(degree)');
title('Reference Signal-- Actual Output . Control Signal __');
AES=sum(abs(ref-y))
echo off
disp('End of mfile2.m')

The absolute error obtained for this system is 446.9001. The graphs in Figure 12 shown
the result of FLC is satisfactory.

Figure 12
Water Level Control in a Surge Tank Using Fuzzy Logic Controller
In this section we use a water level problem for a surge tank to show how to the fuzzy
logic controller work even though the reference point is keep changing fast all the time.
The discrete time equation of a surge tank we use is:
h(k 1) h( k ) T [

19.6h(k )
h 2 (k ) 1

u (k )
] where T is the sampling rate that we set as
h 2 (k ) 1

0.5 second.
However, we have other restrictions on the plant dynamic. In particular, we assume the
plant input, u(k) saturates as +50 and -50. This mean u(k) will be limited in between -50
to +50. Also to ensure that the liquid level never goes negative (which is physically
impossible), we simulate our plant using:

19.6h(k ) u(k )
h(k 1) max{0, h(k ) T[ 2 2 ]} .
h (k ) 1 h (k ) 1
For this application we try to test the ability of fuzzy logic controller on a fast response
plant, therefore the desire output is also change with time such as:
r (k ) cos(0.07 k ) sin(0.05k ) 2.7

The input and output variables are e(k), de(k) and du(k).Here the u(k) can be obtain base
on the equation: u(k) = u(k-1) + du(k).
The code is given as below. Notice that the same code can be found in mFile3.m.
%read FIS from file
f = readfis('fis2.fis');
%f = readfis('mfis1.fis');
%define the plant parameters
T = 0.5;
h0 = 3.5;
p = 1;
q = 2;
%define the gain or scaling factor for all variables
GE = 0.3;
GDE = 1;
GDU = 10;
%number of interval
index = 600;
%initial the level of water to h0
h(1) = h0;
for k = 1 : (index-1)
ref(k) = (cos(0.07*k)) + (sin(0.05*k)) + 2.7;
e(k) = ref(k)-h(k);
%the error use for FIS must be scaled/fuzzify
ef(k) = e(k)*GE;
if k == 1
de(k) = 0;
else
de(k) = e(k) - e(k-1);
end;
%the change of error use for FIS must be scaled/fuzzify
def(k) = de(k)*GDE;
%to void warning message because of bigger than 1 or smaller than -1
if ef(k) < -1

ef(k)= -1;
elseif ef(k) >= 1
ef(k) = 1;
else
ef(k) = ef(k);
end;
if def(k) < -1
def(k)= -1;
elseif def(k) >= 1
def(k) = 1;
else
def(k) = def(k);
end;
%evaluate the FIS based on the error and change of error calculated
duf(k) = evalfis([ef(k) def(k)], f);
%the output of FIS shall be scaled/defuzzify
du(k) = duf(k)*GDU;
if(k > 1)
u(k) = u(k-1) + du(k);
else
u(k) = du(k);
end;
%input to the plant shall be saturated
if (u(k) <= -50)
u(k) = -50;
elseif (u(k) >= 50)
u(k) = 50;
else
u(k) = u(k);
end;
%put the output of FIS into the plant for control purpose
a = -sqrt(19.6*h(k));
b = p*h(k)*h(k) + q;
h(k+1) = h(k) + T*((a/b) + (u(k)/b));
if (h(k+1)) < 0
h(k+1) = 0;
end;
end;
ref(index) = h(index);
%plot the plant output, target output and error of the plant
hold on;
grid;
plot(ref(1:index-1), '-r');
plot(h(1:index-1), 'b');
plot(e(1:index-1),'g');
xlabel('Sampling time step kT where T = 0.5 second');
ylabel('Temperature(degree)');

title('Target Output (red) Actual Output (blue) Error (green)');


AES=sum(abs(ref-h))

The absolute error obtained for this system is 22.9821. The result of this application is
given in Figure 13.

Figure 13
Exercise
For both water level and water temperature control applications, try to fine tune the
scaling/gain parameters of the input/output variables so that the absolute errors are
smaller.

Using Fuzzy Logic Controller in Simulink for Single Link Robot Arm Control
In this demo, the objective is to control the movement of a simple, single-link robot arm,
as shown in the following figure.

Figure 14
d 2 x (t )
dx (t )
10 sin( x(t )) 2
u (t ) . Where
2
dt
dt
x(t) is the angle and u(t) is the control signal (torque). Here we model the single link arm
as a library before use it as a plant to test the fuzzy controller in Simulink. This library is
then saved as myrobotarm.mdl. Type myrobotarm in Matlab console window will
actually call it out. Figure 15 below shown this robot arm has been model as a library.

The equation of motion for the arm is

Figure 15

In Simulink, fuzzy logic controller has been model as a library. If we need to use FIS in
Simulink, 1st, type fuzblock in Matlab console window. The fuzzy models are loaded as
shown in Figure 15.

Figure 15
Once we have both libraries (robot arm and fuzzy controller), start a new Simulink
model, right click robot arm library and select copy, paste it into the new Simulink
model. Repeat the copy and paste but for the fuzzy logic controller. See Figure 16 for
detail. After that, add other model in Simulink such as Sum, Gain and Delay. Notice that
the Simulink model shown in Figure 16 is can be found in sim1.mdl.

Figure 16

However, the Simulink model shown in Figure 16 has not yet ready to run. This is
because the fuzzy logic control must be specific the FIS matrix, where the FIS used to be
design using FIS Editor.
To do this, design a new FIS or open a existing FIS with FIS Editor, select
FileExportWorkSpace. You shall type in a name as you are being as to do so.
E.g., you had just designed an FIS, and you export it to workspace with name fis3.fis.
The next thing to do is come back to your Simulink model, double click the FLC library,
a dialog box is show. See Figure 17 for detail.

Figure 17
As show in Figure 17, you must type in a valid FIS such as fis3.fis which is you just
export to workspace via FIS Editor.
Finally we can start run the Simulink model by select SimulinkStart, a XY plots
shown the output of the fuzzy controlled robot arm compare to random reference points.
The result is shown in Figure 18 below.

Figure 18

Advantage Technique: Adaptive Neuro-Fuzzy-Inference-Systems (ANFIS)


This module is end with a short discussion on ANFIS. ANFIS was 1st proposed by Roger
Jang as a hybrid system between Fuzzy Inference Systems but with neural network
architecture. The learning is required in order to fine-tune the parameters of the
membership functions as well as the parameters of defuzzification. For detail of the
ANFIS, please see [1].
One of the used of ANFIS in control system is to learn the inverse of the plant, so that I
can be used as a controller after training phase. Figure 19 has shown the learning phase of
ANFIS. As an example, we take the water bath temperature system as the target plant to
be controlled. Notice that the learning of ANFIS is based on error back propagation as
well.

y (k 1)

u (k )

ANFIS

y (k ) z 1

z 1
y (k )
y(k 1) f (u (k ), y (k ))

Plant, f

u (k )
Figure 19

After the learning phase is finished, the trained ANFIS is then to be used as a controller
for the plant. The configuration of block to do this is shown in Figure 20.

z 1
y (k )
ANFIS

u (k )

y d (k 1)
Figure 20

Plant, f

y (k 1)

The Matlab source code for training of ANFIS is list out as below. Notice that same
source code can be found mFile4.m.
% =======================
%
Filename : mFile4.m
% =======================
clear;
echo on;
clc;
% ==================================================================
% ANFIS Controller for the Water Bath Temperature Control
% ==================================================================
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%

===================================================================
Problem Statement: To design an ANFIS controller for the
temperature control of a bath described in Module 3.
We shall implement the ANFIS controller using
the direct inverse control strategy shown in Fig 19 and 20.
We first obtain the training data by imposing random input voltages to
the water bath system and recording the corresponding temperatures.
The ANFIS is then trained to identify the inverse model
of the water bath system using the gathered training data.
To start the ANFIS training, we need an FIS matrix that specifies
the structure and initial parameters of the FIS for learning.
The user can use the command ``genfis1" to generate an FIS matrix
from the training data using the grid-type partition
according to the given number and types of membership functions.
In this demonstration, we use five
``gaussmf''-type membership functions.
===================================================================

%
%
%

=====================================
This is the Training program of ANFIS
=====================================

pause % Hit any key to begin this program.


pause % Hit any key to define the plant parameters.
Ts = 25;
p = 1*10^(-4);
q = 8.7*10^(-3);
r = 40.0;
yo = 25;
y(1) = yo;
a = exp(-p*Ts);
b = (q/p)*(1-exp(-p*Ts));
% Hit any key to define the training data.
pause % Here, we use 100 training data. You can try different number of patterns.
for k = 1:120

u(k) = rand(1,1)*5;
y(k+1) = a*y(k)+b/(1+exp(0.5*y(k)-r))*u(k)+(1-a)*yo;
end;
trndata = [y(2:101);y(1:100);u(1:100)]'; %The ' in behind of this code is very important!
pause % Hit any key to train the ANFIS structure.
% please wait ...
nummfs = 5;
mftype = 'gaussmf';
infismat = genfis1(trndata,nummfs,mftype);
[outfismat, error,stepsize] = anfis(trndata, infismat,5);
pause % Hit any key to save the parameters to the disk.
save myanfis.mat outfismat
%To run the "mFile5.m" to test the trained ANFIS.
echo off
disp('End of Mfile4.m')

Another source code listed below is for recall phase for ANFIS when it is used as
controller to control the temperature of water bath. Same code can be found in mFile5.m
% =======================
%
Filename : mFile5.m
% =======================
clear;
echo on;
clc;
%
%
%

==================================================================
ANFIS Controller for the Water Bath Temperature Control
==================================================================

%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%

===================================================================
Problem Statement: To design an ANFIS controller for the
temperature control of a bath described in Module 3.
We shall implement the ANFIS controller using
the direct inverse control strategy shown in Fig 19 and 20.
We first obtain the training data by imposing random input voltages to
the water bath system and recording the corresponding temperatures.
The ANFIS is then trained to identify the inverse model
of the water bath system using the gathered training data.
To start the ANFIS training, we need an FIS matrix that specifies
the structure and initial parameters of the FIS for learning.
The user can use the command ``genfis1" to generate an FIS matrix
from the training data using the grid-type partition
according to the given number and types of membership functions.
In this demonstration, we use five
``gbellmf''-type membership functions.
===================================================================

=====================================

%
%

This is the Testing program of ANFIS


=====================================

pause % Hit any key to begin this program.


pause % Hit any key to load the myanfis.mat
load myanfis.mat
pause % Hit any key to define the plant parameters.
Ts = 25;
p = 1*10^(-4);
q = 8.7*10^(-3);
r = 40.0;
yo = 25;
y(1) = yo;
a = exp(-p*Ts);
b = (q/p)*(1-exp(-p*Ts));
pause % Hit any key to define the reference output.
for k = 1:180
if (k <= 40)
ref(k) = 35;
elseif (k > 40 & k <= 80)
ref(k) = 50;
elseif (k > 80 & k <= 120)
ref(k) = 65;
elseif (k > 120)
ref(k)=80;
end;
end;
pause % Hit any key to test 180 time-steps.
for k=1:179
u(k) = evalfis([ref(k+1) y(k)],outfismat);
if (u(k) >= 5)
u(k)=5;
elseif (u(k) <= 0)
u(k)=0;
else
u(k)=u(k);
end;
y(k+1)=a*y(k)+b/(1+exp(0.5*y(k)-r))*u(k)+(1-a)*yo;
end;
%

...end of testing.

pause % Hit any key to plot the plant input and output, and the reference output.
hold on;
grid;
plot(y(1:180),'.b');
plot(ref(1:180),'-r');
plot(u(1:179),'g');
xlabel('Sampling Time Step KT T = 25 seconds');
ylabel('Temperature(degree)');
title('Reference Signal-- Actual Output . Control Signal __');

AE=sum(abs(ref-y))
echo off
disp('End of mfile5.m')

The total absolute error of this ANFIS controller for this plant is 369.8952, which is
smaller than fuzzy logic controller that we discussed above. Also it produces a stable
control signal u(k). See Figure 21 for detail.

Figure 21

You might also like