Fuzzy
Fuzzy
Fuzzy
Users Guide
Web
Newsgroup
www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com
comp.soft-sys.matlab
suggest@mathworks.com
bugs@mathworks.com
doc@mathworks.com
service@mathworks.com
info@mathworks.com
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Fuzzy Logic Toolbox Users Guide
COPYRIGHT 19952009 The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
governments needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
January 1995
April 1997
January 1998
September 2000
April 2003
June 2004
March 2005
September 2005
March 2006
September 2006
March 2007
September 2007
March 2008
October 2008
March 2009
First printing
Second printing
Third printing
Fourth printing
Fifth printing
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Contents
Getting Started
1
Product Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fuzzy Logic Toolbox Description . . . . . . . . . . . . . . . . . . . . .
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2
1-2
1-3
1-3
1-5
1-5
1-8
1-9
1-10
1-12
1-12
1-12
1-16
1-17
Tutorial
2
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2
2-4
2-4
2-8
2-13
2-16
2-20
2-20
2-21
2-27
2-30
2-31
2-31
2-34
2-35
2-40
2-50
2-54
2-56
2-58
2-59
2-59
2-61
2-67
2-73
2-73
2-76
2-79
2-82
2-82
2-87
2-87
2-94
2-100
2-100
2-104
2-106
vi
Contents
2-108
2-109
2-111
Fuzzy Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What is Data Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fuzzy C-Means Clustering . . . . . . . . . . . . . . . . . . . . . . . . . .
Subtractive Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Clustering Using the Clustering GUI Tool . . . . . . . . .
2-149
2-149
2-149
2-155
2-167
2-111
2-115
2-125
2-129
2-135
2-142
2-171
2-171
2-171
2-172
2-176
Function Reference
3
GUI Tools and Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-2
Membership Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-3
................................
3-4
3-5
vii
Simulink Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-6
4
Block Reference
5
Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-2
.................................
5-3
Membership Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-4
Logical Operators
6
Examples
viii
Contents
Introductory Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-2
A-2
Simulink Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A-2
A-2
A-2
A-2
Bibliography
B
Glossary
Index
ix
Contents
1
Getting Started
Product Overview on page 1-2
What Is Fuzzy Logic? on page 1-5
An Introductory Example: Fuzzy Versus Nonfuzzy Logic on page 1-12
Getting Started
Product Overview
In this section...
Fuzzy Logic Toolbox Description on page 1-2
Installation on page 1-3
Using This Guide on page 1-3
You can change the way any toolbox function works by copying and renaming
the M-file, then modifying your copy. You can also extend the toolbox by
adding your own M-files.
1-2
Product Overview
Secondly, the toolbox provides a number of interactive tools that let you
access many of the functions through a GUI. Together, the GUI-based tools
provide an environment for fuzzy inference system design, analysis, and
implementation.
The third category of tools is a set of blocks for use with Simulink. These
are specifically designed for high speed fuzzy logic inference in the Simulink
environment.
What makes the toolbox so powerful is the fact that most of human reasoning
and concept formation is linked to the use of fuzzy rules. By providing a
systematic framework for computing with fuzzy rules, the toolbox greatly
amplifies the power of human reasoning. Further amplification results
from the use of MATLAB and graphical user interfaces, areas in which The
MathWorks has unparalleled expertise.
Installation
To install this toolbox on a workstation, large machine, or a PC, see the
installation documentation for that platform.
To determine if Fuzzy Logic Toolbox software is already installed on your
system, check for a subdirectory named fuzzy within the main toolbox
directory or folder.
1-3
Getting Started
If you just want to start as soon as possible and experiment, you can open an
example system right away by typing
fuzzy tipper
This displays the Fuzzy Inference System (FIS) editor for an example
decision-making problem that has to do with how to tip in a restaurant.
All toolbox users should use Chapter 4, Functions Alphabetical List for
information on specific tools or functions. Reference descriptions include a
synopsis of the functions syntax, as well as a complete explanation of options
and operation. Many reference descriptions also include helpful examples, a
description of the functions algorithm, and references to additional reading
material. For GUI-based tools, the descriptions include options for invoking
the tool.
1-4
1-5
Getting Started
Another basic concept in FL, which plays a central role in most of its
applications, is that of a fuzzy if-then rule or, simply, fuzzy rule. Although
rule-based systems have a long history of use in Artificial Intelligence (AI),
what is missing in such systems is a mechanism for dealing with fuzzy
consequents and fuzzy antecedents. In fuzzy logic, this mechanism is provided
by the calculus of fuzzy rules. The calculus of fuzzy rules serves as a basis
for what might be called the Fuzzy Dependency and Command Language
(FDCL). Although FDCL is not used explicitly in the toolbox, it is effectively
one of its principal constituents. In most of the applications of fuzzy logic, a
fuzzy logic solution is, in reality, a translation of a human solution into FDCL.
A trend that is growing in visibility relates to the use of fuzzy logic in
combination with neurocomputing and genetic algorithms. More generally,
fuzzy logic, neurocomputing, and genetic algorithms may be viewed as the
principal constituents of what might be called soft computing. Unlike the
traditional, hard computing, soft computing accommodates the imprecision
of the real world. The guiding principle of soft computing is: Exploit
the tolerance for imprecision, uncertainty, and partial truth to achieve
tractability, robustness, and low solution cost. In the future, soft computing
could play an increasingly important role in the conception and design of
systems whose MIQ (Machine IQ) is much higher than that of systems
designed by conventional methods.
Among various combinations of methodologies in soft computing, the
one that has highest visibility at this juncture is that of fuzzy logic and
neurocomputing, leading to neuro-fuzzy systems. Within fuzzy logic, such
systems play a particularly important role in the induction of rules from
observations. An effective method developed by Dr. Roger Jang for this
purpose is called ANFIS (Adaptive Neuro-Fuzzy Inference System). This
method is an important component of the toolbox.
Fuzzy logic is all about the relative importance of precision: How important is
it to be exactly right when a rough answer will do?
You can use Fuzzy Logic Toolbox software with MATLAB technical computing
software as a tool for solving problems with fuzzy logic. Fuzzy logic is a
fascinating area of research because it does a good job of trading off between
significance and precisionsomething that humans have been managing
for a very long time.
1-6
In this sense, fuzzy logic is both old and new because, although the modern
and methodical science of fuzzy logic is still young, the concepts of fuzzy logic
relies on age-old skills of human reasoning.
Precision and Significance in the Real World
A 1500 kg mass
is approaching
your head at
45.3 m/s
Precision
LOOK
OUT!!
Significance
1-7
Getting Started
Input Space
Output Space
tonight's service
quality
Black
Box
1-8
Everything is imprecise if you look closely enough, but more than that, most
things are imprecise even on careful inspection. Fuzzy reasoning builds
this understanding into the process rather than tacking it onto the end.
Fuzzy logic can model nonlinear functions of arbitrary complexity.
You can create a fuzzy system to match any set of input-output data. This
process is made particularly easy by adaptive techniques like Adaptive
Neuro-Fuzzy Inference Systems (ANFIS), which are available in Fuzzy
Logic Toolbox software.
Fuzzy logic can be built on top of the experience of experts.
In direct contrast to neural networks, which take training data and
generate opaque, impenetrable models, fuzzy logic lets you rely on the
experience of people who already understand your system.
Fuzzy logic can be blended with conventional control techniques.
Fuzzy systems dont necessarily replace conventional control methods.
In many cases fuzzy systems augment them and simplify their
implementation.
Fuzzy logic is based on natural language.
The basis for fuzzy logic is the basis for human communication. This
observation underpins many of the other statements about fuzzy logic.
Because fuzzy logic is built on the structures of qualitative description used
in everyday language, fuzzy logic is easy to use.
The last statement is perhaps the most important one and deserves more
discussion. Natural language, which is used by ordinary people on a daily
basis, has been shaped by thousands of years of human history to be
convenient and efficient. Sentences written in ordinary language represent a
triumph of efficient communication.
1-9
Getting Started
do a fine job without using fuzzy logic. However, if you take the time to
become familiar with fuzzy logic, youll see it can be a very powerful tool for
dealing quickly and efficiently with imprecision and nonlinearity.
Fuzzy
Inference
System
Fuzzy
Logic
Toolbox
Simulink
Stand-alone
Fuzzy Engine
User-written
M-files
Other toolboxes
MATLAB
Because of the integrated nature of the MATLAB environment, you can
create your own tools to customize the toolbox or harness it with another
1-10
1-11
Getting Started
1-12
0.25
0.2
tip
0.15
0.1
0.05
0
0
10
service
This relationship does not take into account the quality of the service, so you
need to add a new term to the equation. Because service is rated on a scale of
0 to 10, you might have the tip go linearly from 5% if the service is bad to 25%
if the service is excellent. Now the relation looks like the following plot:
tip=0.20/10*service+0.05
0.25
tip
0.2
0.15
0.1
0.05
0
10
service
The formula does what you want it to do, and is straightforward. However,
you may want the tip to reflect the quality of the food as well. This extension
of the problem is defined as follows.
The Extended Tipping Problem. Given two sets of numbers between 0 and
10 (where 10 is excellent) that respectively represent the quality of the service
and the quality of the food at a restaurant, what should the tip be?
1-13
Getting Started
See how the formula is affected now that you have added another variable.
Try the following equation:
tip = 0.20/20*(service+food)+0.05;
0.25
tip
0.2
0.15
0.1
0.05
10
10
5
food
5
0
service
In this case, the results look satisfactory, but when you look at them closely,
they do not seem quite right. Suppose you want the service to be a more
important factor than the food quality. Specify that service accounts for 80%
of the overall tipping grade and the food makes up the other 20%. Try this
equation:
servRatio=0.8;
tip=servRatio*(0.20/10*service+0.05) + ...
(1-servRatio)*(0.20/10*food+0.05);
0.25
tip
0.2
0.15
0.1
0.05
10
10
5
food
5
0
service
The response is still somehow too uniformly linear. Suppose you want more of
a flat response in the middle, i.e., you want to give a 15% tip in general, but
1-14
want to also specify a variation if the service is exceptionally good or bad. This
factor, in turn, means that the previous linear mappings no longer apply. You
can still use the linear calculation with a piecewise linear construction. Now,
return to the one-dimensional problem of just considering the service. You can
string together a simple conditional statement using breakpoints like this.
if service<3,
tip=(0.10/3)*service+0.05;
elseif service<7,
tip=0.15;
elseif service<=10,
tip=(0.10/3)*(service-7)+0.15;
end
tip
0.2
0.15
0.1
0.05
0
10
service
If you extend this to two dimensions, where you take food into account again,
something like the following output results.
servRatio=0.8;
if service<3,
tip=((0.10/3)*service+0.05)*servRatio + ...
(1-servRatio)*(0.20/10*food+0.05);
elseif service<7,
1-15
Getting Started
tip=(0.15)*servRatio + ...
(1-servRatio)*(0.20/10*food+0.05);
else,
tip=((0.10/3)*(service-7)+0.15)*servRatio + ...
(1-servRatio)*(0.20/10*food+0.05);
end
0.25
tip
0.2
0.15
0.1
0.05
10
10
5
food
5
0
service
The plot looks good, but the function is surprisingly complicated. It was a
little difficult to code this correctly, and it is definitely not easy to modify this
code in the future. Moreover, it is even less apparent how the algorithm works
to someone who did not see the original design process.
1-16
The order in which the rules are presented here is arbitrary. It does not
matter which rules come first. If you want to include the foods effect on the
tip, add the following two rules.
Tipping Problem Rules Food Factor
If food is rancid, then tip is cheap
If food is delicious, then tip is generous
You can combine the two different lists of rules into one tight list of three
rules like so.
Tipping Problem Both Service and Food Factors
If service is poor or the food is rancid, then tip is cheap
If service is good, then tip is average
If service is excellent or food is delicious, then tip is generous
These three rules are the core of your solution. Coincidentally, you have just
defined the rules for a fuzzy logic system. When you give mathematical
meaning to the linguistic variables (what is an average tip, for example?)
you have a complete fuzzy inference system. The methodology of fuzzy logic
must also consider:
How are the rules all combined?
How do I define mathematically what an average tip is?
The next few chapters provide detailed answers to these questions. The
details of the method dont really change much from problem to problemthe
mechanics of fuzzy logic arent terribly complex. What matters is that you
understand that fuzzy logic is adaptable, simple, and easily applied.
Problem Solution
The following plot represents the fuzzy logic system that solves the tipping
problem.
1-17
Getting Started
0.25
tip
0.2
0.15
0.1
0.05
10
10
5
food
5
0
service
This plot was generated by the three rules that accounted for both service
and food factors. The mechanics of how fuzzy inference works is explained
in Overview on page 2-2, Foundations of Fuzzy Logic on page 2-4, and in
Fuzzy Inference Systems on page 2-20. In Building Systems with Fuzzy
Logic Toolbox Software on page 2-31, the entire tipping problem is worked
through using the Fuzzy Logic Toolbox graphical tools.
Observations
Consider some observations about the example so far. You found a piecewise
linear relation that solved the problem. It worked, but it was problematic to
derive, and when you wrote it down as code, it was not very easy to interpret.
Conversely, the fuzzy logic system is based on some common sense statements.
Also, you were able to add two more rules to the bottom of the list that
influenced the shape of the overall output without needing to undo what had
already been done, making the subsequent modification was relatively easy.
Moreover, by using fuzzy logic rules, the maintenance of the structure of
the algorithm decouples along fairly clean lines. The notion of an average
tip might change from day to day, city to city, country to country, but the
underlying logic is the same: if the service is good, the tip should be average.
1-18
As with all code, the more generality that is introduced, the less precise the
algorithm becomes. While you can improve clarity by adding more comments,
1-19
Getting Started
or perhaps rewriting the algorithm in slightly more self-evident ways, but the
piecewise linear methodology is not the optimal way to resolve this issue.
If you remove everything from the algorithm except for three comments, what
remain are exactly the fuzzy logic rules you previously wrote down.
% If service is poor or food is rancid, tip is cheap
% If service is good, tip is average
% If service is excellent or food is delicious, tip is generous
If, as with a fuzzy system, the comment is identical with the code, think
how much more likely your code is to have comments. Fuzzy logic lets the
language that is clearest to you, high level comments, also have meaning to
the machine, which is why it is a very successful technique for bridging the
gap between people and machines.
By making the equations as simple as possible (linear) you make things
simpler for the machine but more complicated for you. However, the
limitation is really no longer the computerit is your mental model of what
the computer is doing. Computers have the ability to make things hopelessly
complex; fuzzy logic reclaims the middle ground and lets the machine work
with your preferences rather than the other way around.
1-20
2
Tutorial
Overview on page 2-2
Foundations of Fuzzy Logic on page 2-4
Fuzzy Inference Systems on page 2-20
Building Systems with Fuzzy Logic Toolbox Software on page 2-31
Building Fuzzy Inference Systems Using Custom Functions on page 2-59
Working from the Command Line on page 2-73
Working in Simulink Environment on page 2-87
Sugeno-Type Fuzzy Inference on page 2-100
anfis and the ANFIS Editor GUI on page 2-107
Fuzzy Clustering on page 2-149
Simulating Fuzzy Inference Systems Using the Fuzzy Inference Engine
on page 2-171
Tutorial
Overview
The point of fuzzy logic is to map an input space to an output space, and the
primary mechanism for doing this is a list of if-then statements called rules.
All rules are evaluated in parallel, and the order of the rules is unimportant.
The rules themselves are useful because they refer to variables and the
adjectives that describe those variables. Before you can build a system that
interprets rules, you must define all the terms you plan on using and the
adjectives that describe them. To say that the water is hot, you need to define
the range that the waters temperature can be expected to vary as well as
what we mean by the word hot. The following diagram provides a roadmap for
the fuzzy inference process. It shows the general description of a fuzzy system
on the left and a specific fuzzy system (the tipping example from Chapter 1,
Getting Started) on the right.
The General Case
Input
Output
A Specific Example
service
tip
Rules
Input
terms
Output
terms
(interpret)
(assign)
service
is interpreted as
{poor,
good,
excellent}
tip
is assigned to be
{cheap,
average,
generous}
2-2
Overview
2-3
Tutorial
Fuzzy Sets
Fuzzy logic starts with the concept of a fuzzy set. A fuzzy set is a set without a
crisp, clearly defined boundary. It can contain elements with only a partial
degree of membership.
To understand what a fuzzy set is, first consider the definition of a classical
set. A classical set is a container that wholly includes or wholly excludes
any given element. For example, the set of days of the week unquestionably
includes Monday, Thursday, and Saturday. It just as unquestionably excludes
butter, liberty, and dorsal fins, and so on.
Shoe
Polish
Monday
Liberty
Thursday
Butter
Saturday
Dorsal
Fins
This type of set is called a classical set because it has been around for a long
time. It was Aristotle who first formulated the Law of the Excluded Middle,
which says X must either be in set A or in set not-A. Another version of this
law is:
Of any subject, one thing must be either asserted or denied.
To restate this law with annotations: Of any subject (say Monday), one thing
(a day of the week) must be either asserted or denied (I assert that Monday
2-4
is a day of the week). This law demands that opposites, the two categories
A and not-A, should between them contain the entire universe. Everything
falls into either one group or the other. There is no thing that is both a day of
the week and not a day of the week.
Now, consider the set of days comprising a weekend. The following diagram
attempts to classify the weekend days.
Shoe
Polish
Monday
Liberty
Saturday
Sunday
Butter
Friday
Thursday
Dorsal
Fins
Most would agree that Saturday and Sunday belong, but what about Friday?
It feels like a part of the weekend, but somehow it seems like it should be
technically excluded. Thus, in the preceding diagram, Friday tries its best to
straddle on the fence. Classical or normal sets would not tolerate this kind of
classification. Either something is in or it is out. Human experience suggests
something different, however, straddling the fence is part of life.
Of course individual perceptions and cultural background must be taken into
account when you define what constitutes the weekend. Even the dictionary is
imprecise, defining the weekend as the period from Friday night or Saturday
to Monday morning. You are entering the realm where sharp-edged, yes-no
logic stops being helpful. Fuzzy reasoning becomes valuable exactly when you
work with how people really perceive the concept weekend as opposed to a
simple-minded classification useful for accounting purposes only. More than
anything else, the following statement lays the foundations for fuzzy logic.
In fuzzy logic, the truth of any statement becomes a matter of degree.
Any statement can be fuzzy. The major advantage that fuzzy reasoning
offers is the ability to reply to a yes-no question with a not-quite-yes-or-no
answer. Humans do this kind of thing all the time (think how rarely you get
a straight answer to a seemingly simple question), but it is a rather new
trick for computers.
2-5
Tutorial
weekend-ness
weekend-ness
1.0
0.0
0.0
Thursday
Friday
Saturday
Sunday
Monday
Thursday
Friday
Saturday
Sunday
2-6
Monday
1.0
weekend-ness
weekend-ness
1.0
0.0
0.0
Thursday
Friday
Saturday
Sunday
Monday
Thursday
Friday
Saturday
Sunday
Monday
By making the plot continuous, you are defining the degree to which any given
instant belongs in the weekend rather than an entire day. In the plot on the
left, notice that at midnight on Friday, just as the second hand sweeps past
12, the weekend-ness truth value jumps discontinuously from 0 to 1. This is
one way to define the weekend, and while it may be useful to an accountant, it
may not really connect with your own real-world experience of weekend-ness.
The plot on the right shows a smoothly varying curve that accounts for the fact
that all of Friday, and, to a small degree, parts of Thursday, partake of the
quality of weekend-ness and thus deserve partial membership in the fuzzy set
of weekend moments. The curve that defines the weekend-ness of any instant
in time is a function that maps the input space (time of the week) to the output
space (weekend-ness). Specifically it is known as a membership function. See
Membership Functions on page 3-3 for a more detailed discussion.
As another example of fuzzy sets, consider the question of seasons. What
season is it right now? In the northern hemisphere, summer officially begins
at the exact moment in the earths orbit when the North Pole is pointed most
directly toward the sun. It occurs exactly once a year, in late June. Using the
astronomical definitions for the season, you get sharp boundaries as shown
on the left in the figure that follows. But what you experience as the seasons
vary more or less continuously as shown on the right in the following figure
(in temperate northern hemisphere climates).
2-7
Tutorial
sprin
g
1.0
summer
fall
winter
sprin
g
1.0
summer
fall
winter
degree
of
membership
degree
of
membership
0.0
0.0
March
June
September
December
March
March
Time of the
year
June
September
December
March
Time of the
year
Membership Functions
A membership function (MF) is a curve that defines how each point in the
input space is mapped to a membership value (or degree of membership)
between 0 and 1. The input space is sometimes referred to as the universe of
discourse, a fancy name for a simple concept.
One of the most commonly used examples of a fuzzy set is the set of tall
people. In this case, the universe of discourse is all potential heights, say from
3 feet to 9 feet, and the word tall would correspond to a curve that defines
the degree to which any person is tall. If the set of tall people is given the
well-defined (crisp) boundary of a classical set, you might say all people taller
than 6 feet are officially considered tall. However, such a distinction is clearly
absurd. It may make sense to consider the set of all real numbers greater
than 6 because numbers belong on an abstract plane, but when we want to
talk about real people, it is unreasonable to call one person short and another
one tall when they differ in height by the width of a hair.
excellent!
You must be
taller than
this line to
be
considered
TALL
2-8
tall (m = 1.0)
sharp-edged
membership
function for
TALL
0.0
height
1.0
degree of
membership,
definitely a tall
person (m = 0.95)
continuous
membership
function for
TALL
0.0
height
Subjective interpretations and appropriate units are built right into fuzzy
sets. If you say Shes tall, the membership function tall should already take
into account whether you are referring to a six-year-old or a grown woman.
Similarly, the units are included in the curve. Certainly it makes no sense to
say Is she tall in inches or in meters?
2-9
Tutorial
2-10
0.75
0.75
0.5
0.5
0.25
0.25
4
6
trimf, P = [3 6 8]
10
4
6
trapmf, P = [1 5 7 8]
trimf
10
trapmf
0.75
0.75
0.75
0.5
0.5
0.5
0.25
0.25
0.25
0
0
0
2
4
6
gaussmf, P = [2 5]
gaussmf
10
4
6
gauss2mf, P = [1 3 3 4]
gauss2mf
10
4
6
gbellmf, P = [2 4 6]
10
gbellmf
2-11
Tutorial
0.75
0.75
0.75
0.5
0.5
0.5
0.25
0.25
0.25
0
0
0
2
4
6
sigmf, P = [2 4]
10
4
6
dsigmf, P = [5 2 5 7]
sigmf
10
4
6
psigmf, P = [2 3 5 8]
10
psigmf
dsigmf
0.75
0.75
0.75
0.5
0.5
0.5
0.25
0.25
0.25
0
0
4
6
zmf, P = [3 7]
zmf
10
0
2
4
6
pimf, P = [1 4 5 10]
pimf
10
4
6
smf, P = [1 8]
smf
2-12
10
A fuzzy set admits the possibility of partial membership in it. (e.g., Friday
is sort of a weekend day, the weather is rather hot).
The degree an object belongs to a fuzzy set is denoted by a membership
value between 0 and 1. (e.g., Friday is a weekend day to the degree 0.8).
A membership function associated with a given fuzzy set maps an input
value to its appropriate membership value.
Logical Operations
Now that you understand the fuzzy inference, you need to see how fuzzy
inference connects with logical operations.
The most important thing to realize about fuzzy logical reasoning is the fact
that it is a superset of standard Boolean logic. In other words, if you keep the
fuzzy values at their extremes of 1 (completely true), and 0 (completely false),
standard logical operations will hold. As an example, consider the following
standard truth tables.
A
A and B
A or B
not A
AND
OR
NOT
Now, because in fuzzy logic the truth of any statement is a matter of degree,
can these truth tables be altered? The input values can be real numbers
between 0 and 1. What function preserves the results of the AND truth table
(for example) and also extend to all real numbers between 0 and 1?
One answer is the min operation. That is, resolve the statement A AND B,
where A and B are limited to the range (0,1), by using the function min(A,B).
Using the same reasoning, you can replace the OR operation with the max
function, so that A OR B becomes equivalent to max(A,B). Finally, the
operation NOT A becomes equivalent to the operation 1 A . Notice how the
previous truth table is completely unchanged by this substitution.
2-13
Tutorial
min(A,B)
max(A,B)
1-A
AND
OR
NOT
Moreover, because there is a function behind the truth table rather than just
the truth table itself, you can now consider values other than 1 and 0.
The next figure uses a graph to show the same information. In this figure, the
truth table is converted to a plot of two fuzzy sets applied together to create
one fuzzy set. The upper part of the figure displays plots corresponding to the
preceding two-valued truth tables, while the lower part of the figure displays
how the operations work over a continuously varying range of truth values A
and B according to the fuzzy operations you have defined.
A
B
Two-valued
logic
A or B
A and
B
not A
Multivalued
logic
A and
B
AND
min(A,B)
2-14
not A
A or B
OR
max(A,B)
NOT
(1-A)
Given these three functions, you can resolve any construction using fuzzy sets
and the fuzzy logical operation AND, OR, and NOT.
2-15
Tutorial
If-Then Rules
Fuzzy sets and fuzzy operators are the subjects and verbs of fuzzy logic. These
if-then rule statements are used to formulate the conditional statements that
comprise fuzzy logic.
A single fuzzy if-then rule assumes the form
if x is A then y is B
where A and B are linguistic values defined by fuzzy sets on the ranges
(universes of discourse) X and Y, respectively. The if-part of the rule x is A
is called the antecedent or premise, while the then-part of the rule y is B is
called the consequent or conclusion. An example of such a rule might be
2-16
2-17
Tutorial
if temperature is cold then hot water valve is open and cold water valve is
shut
in which case all consequents are affected equally by the result of the
antecedent. How is the consequent affected by the antecedent? The
consequent specifies a fuzzy set be assigned to the output. The implication
function then modifies that fuzzy set to the degree specified by the antecedent.
The most common ways to modify the output fuzzy set are truncation using
the min function (where the fuzzy set is truncated as shown in the following
figure) or scaling using the prod function (where the output fuzzy set is
squashed). Both are supported by the toolbox, but you use truncation for
the examples in this section.
Antecedent
If
service is excellent
or
food is delicious
excellent
1. Fuzzify
inputs
Consequent
then
tip = generous
then
tip = generous
0.7
delicious
0.0
food (crisp)
service (crisp)
(food==delicious) = 0 .7
(service==excellent) = 0 .0
If
( 0.0
or
2. Apply
OR operator
(max)
0.7 )
0.7
0.7
0.0
3. Apply
implication
operator (min)
If
( 0.7 )
then
tip = generous
0.7
geneo
rus
min(0.7, generous)
2-18
tip (fuzzy)
multiple parts to the antecedent, apply fuzzy logic operators and resolve
the antecedent to a single number between 0 and 1. This is the degree of
support for the rule.
3 Apply implication method: Use the degree of support for the entire
rule to shape the output fuzzy set. The consequent of a fuzzy rule
assigns an entire fuzzy set to the output. This fuzzy set is represented
by a membership function that is chosen to indicate the qualities of the
consequent. If the antecedent is only partially true, (i.e., is assigned a
value less than 1), then the output fuzzy set is truncated according to the
implication method.
In general, one rule alone is not effective. Two or more rules that can play
off one another are needed. The output of each rule is a fuzzy set. The
output fuzzy sets for each rule are then aggregated into a single output fuzzy
set. Finally the resulting set is defuzzified, or resolved to a single number.
Fuzzy Inference Systems on page 2-20 shows how the whole process works
from beginning to end for a particular type of fuzzy inference system called
a Mamdani type.
2-19
Tutorial
2-20
Rule 2
Rule 3
Input 1
Service (0-10)
Input 2
Food (0-10)
S
The results of the
rules are combined
and distilled
(defuzzified).
Output
Tip (5-25%)
The result is a
crisp (non-fuzzy)
number.
2-21
Tutorial
Information flows from left to right, from two inputs to a single output. The
parallel nature of the rules is one of the more important aspects of fuzzy logic
systems. Instead of sharp switching between modes based on breakpoints,
logic flows smoothly from regions where the systems behavior is dominated
by either one rule or another.
Fuzzy inference process comprises of five parts: fuzzification of the input
variables, application of the fuzzy operator (AND or OR) in the antecedent,
implication from the antecedent to the consequent, aggregation of the
consequents across the rules, and defuzzification. These sometimes cryptic
and odd names have very specific meaning that are defined in the following
steps.
2-22
1. Fuzzify
inputs.
0.7
delicious
Result of
fuzzification
food is delicious
food = 8
input
In this manner, each input is fuzzified over all the qualifying membership
functions required by the rules.
2-23
Tutorial
selects the maximum of the two values, 0.7, and the fuzzy operation for rule 3
is complete. The probabilistic OR method would still result in 0.7.
1. Fuzzify
inputs.
2. Apply
OR operator (max).
excellent
0.7
0.0
service is excellent
or
delicious
0.0
0.7
result of
fuzzy operator
food is delicious
service = 3
food = 8
input 1
input 2
2-24
Antecedent
Consequent
3. Apply
Implication
operator (min).
2. Apply
OR operator (max).
1. Fuzzify
inputs.
excellent
generous
delicious
If
service is excellent
or
food is delicious
service = 3
food = 8
input 1
input 2
then
tip = generous
result of
implication
2-25
Tutorial
In the following diagram, all three rules have been placed together to show
how the output of each rule is combined, or aggregated, into a single fuzzy set
whose membership function assigns a weighting for every output (tip) value.
1.
poor
3. Apply
implication
method (min).
2. Apply
fuzzy
operation
(OR = max).
1. Fuzzify inputs.
cheap
rancid
0
If
service is poor
or
food is rancid
25%
25%
25%
tip = average
25%
25%
tip = cheap
then
average
2.
rule 2 has
no dependency
on input 2
good
If
3.
then
service is good
excellent
generous
delicious
0
If
service is excellent
or
food is delicious
service = 3
food = 8
input 1
input 2
then
25%
tip = generous
4. Apply
aggregation
method (max).
25%
Result of
aggregation
Step 5. Defuzzify
The input for the defuzzification process is a fuzzy set (the aggregate output
fuzzy set) and the output is a single number. As much as fuzziness helps
the rule evaluation during the intermediate steps, the final desired output
for each variable is generally a single number. However, the aggregate of a
fuzzy set encompasses a range of output values, and so must be defuzzified in
order to resolve a single output value from the set.
Perhaps the most popular defuzzification method is the centroid calculation,
which returns the center of area under the curve. There are five built-in
2-26
25%
5. Defuzzify the
aggregate output
(centroid).
tip = 16.7%
Result of
defuzzification
2-27
Tutorial
Interpreting the
fuzzy inference
diagram
1. if
and
then
2. if
and
then
input 1
input 2
output
In this figure, the flow proceeds up from the inputs in the lower left, then
across each row, or rule, and then down the rule outputs to finish in the lower
right. This compact flow shows everything at once, from linguistic variable
fuzzification all the way through defuzzification of the aggregate output.
2-28
The following figure shows the actual full-size fuzzy inference diagram. There
is a lot to see in a fuzzy inference diagram, but after you become accustomed
to it, you can learn a lot about a system very quickly. For instance, from this
diagram with these particular inputs, you can easily see that the implication
method is truncation with the min function. The max function is being used
for the fuzzy OR operation. Rule 3 (the bottom-most row in the diagram
shown previously) is having the strongest influence on the output. and so on.
The Rule Viewer described in The Rule Viewer on page 2-54 is a MATLAB
implementation of the fuzzy inference diagram.
2-29
Tutorial
Customization
One of the primary goals of Fuzzy Logic Toolbox software is to have an
open and easily modified fuzzy inference system structure. The toolbox is
designed to give you as much freedom as possible, within the basic constraints
of the process described, to customize the fuzzy inference process for your
application.
Building Systems with Fuzzy Logic Toolbox Software on page 2-31 describes
exactly how to build and implement a fuzzy inference system using the tools
provided. To learn how to customize a fuzzy inference system, see Building
Fuzzy Inference Systems Using Custom Functions on page 2-59.
2-30
2-31
Tutorial
Rule Editor
Rule Viewer
Surface Viewer
These GUIs are dynamically linked, in that changes you make to the FIS
using one of them, can affect what you see on any of the other open GUIs. You
can have any or all of them open for any given system.
In addition to these five primary GUIs, the toolbox includes the graphical
ANFIS Editor GUI, which is used for building and analyzing Sugeno-type
adaptive neuro-fuzzy inference systems. The ANFIS Editor GUI is discussed
in anfis and the ANFIS Editor GUI on page 2-107.
FIS Editor
Membership
Function Editor
Rule Editor
Fuzzy
Inference
System
Read-only
tools
Rule Viewer
Surface Viewer
The FIS Editor handles the high-level issues for the system: How many input
and output variables? What are their names? Fuzzy Logic Toolbox software
2-32
does not limit the number of inputs. However, the number of inputs may be
limited by the available memory of your machine. If the number of inputs is
too large, or the number of membership functions is too big, then it may also
be difficult to analyze the FIS using the other GUI tools.
The Membership Function Editor is used to define the shapes of all the
membership functions associated with each variable.
The Rule Editor is for editing the list of rules that defines the behavior of
the system.
The Rule Viewer and the Surface Viewer are used for looking at, as opposed
to editing, the FIS. They are strictly read-only tools. The Rule Viewer is
a MATLAB technical computing environment based display of the fuzzy
inference diagram shown at the end of the last section. Used as a diagnostic, it
can show (for example) which rules are active, or how individual membership
function shapes are influencing the results. The Surface Viewer is used
to display the dependency of one of the outputs on any one or two of the
inputsthat is, it generates and plots an output surface map for the system.
This section began with an illustration similar to the following one describing
the main parts of a fuzzy inference system, only the next one shows how
the three editors fit together. The two viewers examine the behavior of the
entire system.
The General Case...
A Specific Example...
Input
service
Output
tip
Rules
Input
terms
Output
terms
(interpret)
(assign)
service =
tip =
{poor,
good,
excellent}
{cheap,
average,
generous}
The Membership
Function Editor
The five primary GUIs can all interact and exchange information. Any one of
them can read and write both to the workspace and to a file (the read-only
viewers can still exchange plots with the workspace and save them to a file).
2-33
Tutorial
For any fuzzy inference system, any or all of these five GUIs may be open.
If more than one of these editors is open for a single system, the various
GUI windows are aware of the existence of the others, and, if necessary,
updates related windows. Thus, if the names of the membership functions
are changed using the Membership Function Editor, those changes are
reflected in the rules shown in the Rule Editor. The editors for any number
of different FIS systems may be open simultaneously. The FIS Editor, the
Membership Function Editor, and the Rule Editor can all read and modify
the FIS data, but the Rule Viewer and the Surface Viewer do not modify the
FIS data in any way.
Getting Started
Well start with a basic description of a two-input, one-output tipping problem
(based on tipping practices in the U.S.).
2-34
Obviously the numbers and the shape of the curve are subject to local
traditions, cultural bias, and so on, but the three rules are generally universal.
Now that you know the rules and have an idea of what the output should look
like, begin working with the GUI tools to construct a fuzzy inference system
for this decision process.
2-35
Tutorial
Double-click an input
variable icon to open the
Membership Function Editor.
Double-click the
system diagram to
open the Rule Editor.
2-36
The diagram at the top shows the names of each input variable on the left,
and those of each output variable on the right. The sample membership
functions shown in the boxes are just icons and do not depict the actual
shapes of the membership functions:
Below the diagram is the name of the system and the type of inference
used. The default, Mamdani-type inference, is what is described so far and
what you continue to use for this example. Another slightly different type
of inference, called Sugeno-type inference, is also available. This method is
explained in Sugeno-Type Fuzzy Inference on page 2-100.
Below the name of the fuzzy inference system, on the left side of the figure,
are the pop-up menus that allow you to modify the various pieces of the
inference process.
On the right side at the bottom of the figure is the area that displays the
name of either an input or output variable, its associated membership
function type, and its range.
The latter two fields are specified only after the membership functions
have been.
Below that region are the Help and Close buttons that call up online help
and close the window, respectively. At the bottom is a status line that
relays information about the system.
The following discussion tells you how to build a new fuzzy inference system
from scratch. If you want to save time and follow along quickly, you can load
the prebuilt system by typing
fuzzy tipper
This command loads the FIS associated with the file tipper.fis (the .fis
is implied) and launches the FIS Editor. However, if you load the prebuilt
system, you will not build rules or construct membership functions.
To start building the Fuzzy Inference System described in The Basic Tipping
Problem on page 2-34 from scratch, type the following command at the
MATLAB prompt.
fuzzy
2-37
Tutorial
The generic untitled FIS Editor opens, with one input labeled input1, and
one output labeled output1.
In this example, you construct a two-input, one output system. The two
inputs are service and food. The one output is tip.
To add a second input variable and change the variable names to reflect these
designations:
1 Select Edit > Add variable > Input.
2-38
The diagram is updated to reflect the new names of the input and output
variables. There is now a new variable in the workspace called tipper that
contains all the information about this system. By saving to the workspace
with a new name, you also rename the entire system. Your window looks
something like the following diagram.
2-39
Tutorial
Leave the inference options in the lower left in their default positions for now.
You have entered all the information you need for this particular GUI. Next,
define the membership functions associated with each of the variables. To do
this, open the Membership Function Editor.
You can open the Membership Function Editor in one of three ways:
Within the FIS Editor window, select Edit > Membership Functions..
Within the FIS Editor window, double-click the blue icon called tip.
At the command line, type mfedit.
2-40
Editor shares some features with the FIS Editor, as shown in the next figure.
In fact, all of the five basic GUI tools have similar menu options, status lines,
and Help and Close buttons.
Menu commands for
saving, opening, and editing
a fuzzy system.
2-41
Tutorial
When you open the Membership Function Editor to work on a fuzzy inference
system that does not already exist in the workspace, there are no membership
functions associated with the variables that you defined with the FIS Editor.
On the upper-left side of the graph area in the Membership Function Editor is
a Variable Palette that lets you set the membership functions for a given
variable.
To set up the membership functions associated with an input or an output
variable for the FIS, select a FIS variable in this region by clicking it.
Next select the Edit pull-down menu, and choose Add MFs .. A new window
appears, which allows you to select both the membership function type and
the number of membership functions associated with the selected variable.
In the lower-right corner of the window are the controls that let you change
the name, type, and parameters (shape), of the membership function, after
it is selected.
The membership functions from the current variable are displayed in the main
graph. These membership functions can be manipulated in two ways. You
2-42
can first use the mouse to select a particular membership function associated
with a given variable quality, (such as poor, for the variable, service), and
then drag the membership function from side to side. This action affects the
mathematical description of the quality associated with that membership
function for a given variable. The selected membership function can also be
tagged for dilation or contraction by clicking on the small square drag points
on the membership function, and then dragging the function with the mouse
toward the outside, for dilation, or toward the inside, for contraction. This
action changes the parameters associated with that membership function.
Below the Variable Palette is some information about the type and name of
the current variable. There is a text field in this region that lets you change
the limits of the current variables range (universe of discourse) and another
that lets you set the limits of the current plot (which has no real effect on
the system).
The process of specifying the membership functions for the two input tipping
example, tipper, is as follows:
1 Double-click the input variable service to open the Membership Function
Editor.
2-43
Tutorial
2 In the Membership Function Editor, enter [0 10] in the Range and the
Type.
2-44
2-45
Tutorial
b Click on the curve named mf2 to select it, and specify the following fields
2-46
5 In the FIS Variables area, click the input variable food to select it.
6 Enter [0 10] in the Range and the Display Range fields.
7 Create the membership functions for the input variable food.
a Select Edit > Remove All MFs to remove the default Membership
2-47
Tutorial
8 Rename the membership functions for the input variable food, and specify
their parameters:
a In the FIS Variables area, click the input variable food to select it.
b Click on the curve named mf1, and specify the following fields in the
Name field.
Reset the associated parameters if desired.
9 Click on the output variable tip to select it.
10 Enter [0 30] in the Range and the Display Range fields to cover the
output range.
The inputs ranges from 0 to 10, but the output is a tip between 5% and 25%.
11 Rename the default triangular membership functions for the output
2-48
Now that the variables have been named and the membership functions
have appropriate shapes and names, you can enter the rules. To call up the
Rule Editor, go to the Edit menu and select Rules, or type ruleedit at the
command line.
2-49
Tutorial
Link input
statements in rules.
This status line
describes the most
recent operation.
Constructing rules using the graphical Rule Editor interface is fairly self
evident. Based on the descriptions of the input and output variables defined
with the FIS Editor, the Rule Editor allows you to construct the rule
statements automatically, From the GUI, you can:
Create rules by selecting an item in each input and output variable box,
and one Connection item and clicking Add Rule. You can choose none as
2-50
one of the variable qualities to exclude that variable from a given rule and
choose not under any variable name to negate the associated quality.
Delete a rule by selecting the rule and clicking Delete Rule.
Edit a rule by changing the selection in the variable box and clicking
Change Rule.
Specify weight to a rule by typing in a desired number between 0 and 1 in
Weight. If you do not specify the weight, it is assumed to be unity (1).
Similar to those in the FIS Editor and the Membership Function Editor, the
Rule Editor has the menu bar and the status line. The menu items allow you
to open, close, save and edit a fuzzy system using the five basic GUI tools.
From the menu, you can also:
Set the format for the display by selecting Options > Format.
Set the language by selecting Options > Language.
You can access information about the Rule Editor by clicking Help and close
the GUI using Close.
To insert the first rule in the Rule Editor, select the following:
poor under the variable service
rancid under the variable food
The or radio button, in the Connection block
cheap, under the output variable, tip.
The resulting rule is
1. If (service is poor) or (food is rancid) then (tip is cheap) (1)
The numbers in the parentheses represent weights.
Follow a similar procedure to insert the second and third rules in the Rule
Editor to get
1 If (service is poor) or (food is rancid) then (tip is cheap) (1)
2-51
Tutorial
To change a rule, first click on the rule to be changed. Next make the desired
changes to that rule, and then click Change rule. For example, to change
the first rule to
1. If (service not poor) or (food not rancid) then (tip is not cheap) (1)
Select the not check box under each variable, and then click Change rule.
The Format pop-up menu from the Options menu indicates that you are
looking at the verbose form of the rules. Try changing it to symbolic. You
will see
1. (service==poor) | (food==rancid) => (tip=cheap) (1)
2. (service==good) => (tip=average) (1)
3. (service==excellent) | (food==delicious) => (tip=generous) (1)
There is not much difference in the display really, but it is slightly more
language neutral, because it does not depend on terms like if and then. If
you change the format to indexed, you see an extremely compressed version
of the rules.
1 1, 1 (1) : 2
2 0, 2 (1) : 1
3 2, 3 (1) : 2
This is the version of the rules that the machine deals with.
The first column in this structure corresponds to the input variables.
The second column corresponds to the output variable.
The third column displays the weight applied to each rule.
The fourth column is shorthand that indicates whether this is an OR (2)
rule or an AND (1) rule.
The numbers in the first two columns refer to the index number of the
membership function.
2-52
2-53
Tutorial
The Rule Viewer displays a roadmap of the whole fuzzy inference process. It
is based on the fuzzy inference diagram described in the previous section. You
see a single figure window with 10 plots nested in it. The three plots across
the top of the figure represent the antecedent and consequent of the first rule.
Each rule is a row of plots, and each column is a variable. The rule numbers
are displayed on the left of each row. You can click on a rule number to view
the rule in the status line.
The first two columns of plots (the six yellow plots) show the membership
functions referenced by the antecedent, or the if-part of each rule.
The third column of plots (the three blue plots) shows the membership
functions referenced by the consequent, or the then-part of each rule.
2-54
Notice that under food, there is a plot which is blank. This corresponds to
the characterization of none for the variable food in the second rule.
The fourth plot in the third column of plots represents the aggregate
weighted decision for the given inference system.
This decision will depend on the input values for the system. The
defuzzified output is displayed as a bold vertical line on this plot.
The variables and their current values are displayed on top of the columns.
In the lower left, there is a text field Input in which you can enter specific
input values. For the two-input system, you will enter an input vector, [9 8],
for example, and then pressEnter. You can also adjust these input values by
clicking on any of the three plots for each input. This will move the red index
line horizontally, to the point where you have clicked. Alternatively, you can
also click and drag this line in order to change the input values. When you
release the line, (or after manually specifying the input), a new calculation is
performed, and you can see the whole fuzzy inference process take place:
Where the index line representing service crosses the membership function
line service is poor in the upper-left plot determines the degree to which
rule one is activated.
A yellow patch of color under the actual membership function curve is used
to make the fuzzy membership value visually apparent.
Each of the characterizations of each of the variables is specified with respect
to the input index line in this manner. If you follow rule 1 across the top of
the diagram, you can see the consequent tip is cheap has been truncated to
exactly the same degree as the (composite) antecedentthis is the implication
process in action. The aggregation occurs down the third column, and the
resultant aggregate plot is shown in the single plot appearing in the lower
right corner of the plot field. The defuzzified output value is shown by the
thick line passing through the aggregate fuzzy set.
You can shift the plots using left, right, down, and up. The menu items allow
you to save, open, or edit a fuzzy system using any of the five basic GUI tools.
The Rule Viewer allows you to interpret the entire fuzzy inference process
at once. The Rule Viewer also shows how the shape of certain membership
functions influences the overall result. Because it plots every part of every
2-55
Tutorial
rule, it can become unwieldy for particularly large systems, but, for a
relatively small number of inputs and outputs, it performs well (depending on
how much screen space you devote to it) with up to 30 rules and as many as
6 or 7 variables.
The Rule Viewer shows one calculation at a time and in great detail. In this
sense, it presents a sort of micro view of the fuzzy inference system. If you
want to see the entire output surface of your systemthe entire span of the
output set based on the entire span of the input set you need to open up the
Surface Viewer. This viewer is the last of the five basic Fuzzy Logic Toolbox
GUI tools. To open the Surface Viewer, select Surface from the View menu.
2-56
Upon opening the Surface Viewer, you see a three-dimensional curve that
represents the mapping from food and service quality to tip amount. Because
this curve represents a two-input one-output case, you can see the entire
mapping in one plot. When we move beyond three dimensions overall, we
start to encounter trouble displaying the results.
Accordingly, the Surface Viewer is equipped with drop-down menus X
(input):, Y (input): and Z (output): that let you select any two inputs
and any one output for plotting. Below these menus are two input fields X
grids: and Y grids: that let you specify how many x-axis and y-axis grid
lines you want to include. This capability allows you to keep the calculation
time reasonable for complex problems.
If you want to create a smoother plot, use the Plot points field to specify the
number of points on which the membership functions are evaluated in the
input or output range. By default, the value of this field is 101.
Clicking Evaluate initiates the calculation, and the plot is generated after
the calculation is complete. To change the x-axis or y-axis grid after the
surface is in view, change the appropriate input field, and press Enter. The
surface plot is updated to reflect the new grid settings.
The Surface Viewer has a special capability that is very helpful in cases with
two (or more) inputs and one output: you can grab the axes, using the mouse
and reposition them to get a different three-dimensional view on the data.
The Ref. Input field is used in situations when there are more inputs
required by the system than the surface is mapping. You can edit this field to
explicitly set inputs not specified in the surface plot.
Suppose you have a four-input one-output system and would like to see the
output surface. The Surface Viewer can generate a three-dimensional output
surface where any two of the inputs vary, but two of the inputs must be held
constant because computer monitors cannot display a five-dimensional shape.
In such a case, the input is a four-dimensional vector with NaNs holding the
place of the varying inputs while numerical values indicates those values that
remain fixed. A NaN is the IEEE symbol for Not a Number.
2-57
Tutorial
The menu items allow you to open, close, save and edit a fuzzy system using
the five basic GUI tools. You can access information about the Surface Viewer
by clicking Help and close the GUI using Close.
This concludes the quick walk-through of each of the main GUI tools. For the
tipping problem, the output of the fuzzy system matches your original idea of
the shape of the fuzzy mapping from service to tip fairly well. In hindsight,
you might say, Why bother? I could have just drawn a quick lookup table
and been done an hour ago! However, if you are interested in solving an
entire class of similar decision-making problems, fuzzy logic may provide
an appropriate tool for the solution, given its ease with which a system can
be quickly modified.
2-58
page 2-50.
Rules define the logical relationship between the inputs and the outputs.
2-59
Tutorial
6 Select View > Surface to view the output of the fuzzy inference system in
2-60
working directory.
To learn how to create MATLAB functions, see the Functions and Scripts
section in the MATLAB documentation.
The following code is an example of a multi-step custom membership
function, custmf1, that depends on eight parameters between 0 and 10.
% Function to generate a multi-step custom membership function
% using 8 parameters for the input argument x
function out = custmf1(x, params)
for i=1:length(x)
if x(i)<params(1)
y(i)=params(1);
elseif x(i)<params(2)
y(i)=params(2);
elseif x(i)<params(3)
y(i)=params(3);
elseif x(i)<params(4)
y(i)=params(4);
elseif x(i)<params(5)
y(i)=params(5);
elseif x(i)<params(6)
y(i)=params(6);
elseif x(i)<params(7)
y(i)=params(7);
elseif x(i)<params(8)
y(i)=params(8);
2-61
Tutorial
else
y(i)=0;
end
end
out=.1*y'; % scaling the output to lie between 0 and 1
2-62
3 In the FIS Editor, select Edit > Membership Functions to open the
2-63
Tutorial
box:
a Specify a name for the custom membership function in the MF name
field.
Note When adding additional custom membership functions, you must
specify a different MF name for each function.
b Specify the name of the custom membership function M-file in the M-file
2-64
2-65
Tutorial
This action also adds the custom membership function to the Rule Viewer,
and is now available for creating rules for the fuzzy inference process. To
view the custom function in the Rule Viewer, select Edit > Rules in either
the FIS Editor or the Membership Function Editor.
2-66
2-67
Tutorial
For a matrix x, min(x) returns a row vector containing the minimum element
from each column.
x=[1 2 3 4;5 6 7 8;9 10 11 12];
min(x)
ans =
1
2
3
4
For N-D arrays, min(x) operates along the first non-singleton dimension.
The function min(x,y) returns an array that is same size as x and y with the
minimum elements from x or y. Either of the input arguments can be a scalar.
Functions such as max, and prod operate in a similar manner.
2-68
4];
2];
2
2
2-69
Tutorial
2-70
1 In the lower-left panel of the FIS Editor, select Custom from the drop-down
menu corresponding to the inference method for which you want to specify
the custom function.
This action opens a dialog box where you specify the name of the custom
inference function.
2 In the Method name field, specify the name of the custom inference
2-71
Tutorial
The custom function replaces the built-in function when building the fuzzy
inference system.
3 To specify custom functions for other inference methods, repeat steps
1 and 2.
2-72
'tipper'
'mamdani'
'min'
'max'
'centroid'
'min'
'max'
[1x2 struct]
[1x1 struct]
[1x3 struct]
The labels on the left of this listing represent the various components of the
MATLAB structure associated with tipper.fis. You can access the various
components of this structure by typing the component name after typing a.
At the MATLAB command line, type
a.type
2-73
Tutorial
The function
getfis(a)
returns almost the same structure information that typing a, alone does.
getfis(a) returns
Name
= tipper
Type
= mamdani
NumInputs = 2
InLabels =
service
food
NumOutputs = 1
OutLabels =
tip
NumRules = 3
AndMethod = min
OrMethod = max
ImpMethod = min
AggMethod = max
DefuzzMethod = centroid
Some of these fields are not part of the structure, a. Thus, you cannot get
information by typing a.Inlabels, but you can get it by typing
getfis(a,'Inlabels')
Similarly, you can obtain structure information using getfis in this manner.
getfis(a,'input',1)
getfis(a,'output',1)
getfis(a,'input',1,'mf',1)
2-74
or
a.input(1).mf(1)
Now the FIS structure a has been changed to reflect the new name. If you
want a little more insight into this FIS structure, try
showfis(a)
This syntax returns a printout listing all the information about a. This
function is intended more for debugging than anything else, but it shows all
the information recorded in the FIS structure
Because the variable, a, designates the fuzzy tipping system, you can display
any of the GUIs for the tipping system directly from the command line. Any of
the following functions will display the tipping system with the associated
GUI:
fuzzy(a) displays the FIS Editor.
mfedit(a) displays the Membership Function Editor.
2-75
Tutorial
2-76
After closing any open MATLAB figures or GUI windows, the function plotmf
plots all the membership functions associated with a given variable as follows.
plotmf(a,'input',1)
poor
1
good
excellent
Degree of membership
0.8
0.6
0.4
0.2
5
service
10
plotmf(a,'output',1)
2-77
Tutorial
cheap
average
generous
Degree of membership
0.8
0.6
0.4
0.2
10
15
tip
20
25
30
2-78
25
tip
20
15
10
5
10
8
10
6
8
6
2
food
2
0
service
2-79
Tutorial
The entry in column 2 is the index number for the membership function
associated with input 2, and so on.
The next n columns work the same way for the outputs.
Column m + n + 1 is the weight associated with that rule (typically 1) and
column m + n + 2 specifies the connective used (where AND = 1 and OR = 2).
The structure associated with the preceding rule is
1 3 2 0.5 2
This sample code shows one way you can build the entire tipping system from
the command line, using the MATLAB structure syntax.
a=newfis('tipper');
a.input(1).name='service';
a.input(1).range=[0 10];
a.input(1).mf(1).name='poor';
a.input(1).mf(1).type='gaussmf';
a.input(1).mf(1).params=[1.5 0];
a.input(1).mf(2).name='good';
a.input(1).mf(2).type='gaussmf';
a.input(1).mf(2).params=[1.5 5];
a.input(1).mf(3).name='excellent';
a.input(1).mf(3).type='gaussmf';
a.input(1).mf(3).params=[1.5 10];
a.input(2).name='food';
a.input(2).range=[0 10];
a.input(2).mf(1).name='rancid';
a.input(2).mf(1).type='trapmf';
a.input(2).mf(1).params=[-2 0 1 3];
a.input(2).mf(2).name='delicious';
a.input(2).mf(2).type='trapmf';
a.input(2).mf(2).params=[7 9 10 12];
a.output(1).name='tip';
a.output(1).range=[0 30];
a.output(1).mf(1).name='cheap'
a.output(1).mf(1).type='trimf';
a.output(1).mf(1).params=[0 5 10];
a.output(1).mf(2).name='average';
2-80
a.output(1).mf(2).type='trimf';
a.output(1).mf(2).params=[10 15 20];
a.output(1).mf(3).name='generous';
a.output(1).mf(3).type='trimf';
a.output(1).mf(3).params=[20 25 30];
a.rule(1).antecedent=[1 1];
a.rule(1).consequent=[1];
a.rule(1).weight=1;
a.rule(1).connection=2;
a.rule(2).antecedent=[2 0];
a.rule(2).consequent=[2];
a.rule(2).weight=1;
a.rule(2).connection=1;
a.rule(3).antecedent=[3 2];
a.rule(3).consequent=[3];
a.rule(3).weight=1;
a.rule(3).connection=2
Alternatively, you can build the entire tipping system from the command
line using Fuzzy Logic Toolbox commands. These commands are in the
mktipper.m demo file.
a=newfis('tipper');
a=addvar(a,'input','service',[0 10]);
a=addmf(a,'input',1,'poor','gaussmf',[1.5 0]);
a=addmf(a,'input',1,'good','gaussmf',[1.5 5]);
a=addmf(a,'input',1,'excellent','gaussmf',[1.5 10]);
a=addvar(a,'input','food',[0 10]);
a=addmf(a,'input',2,'rancid','trapmf',[-2 0 1 3]);
a=addmf(a,'input',2,'delicious','trapmf',[7 9 10 12]);
a=addvar(a,'output','tip',[0 30]);
a=addmf(a,'output',1,'cheap','trimf',[0 5 10]);
a=addmf(a,'output',1,'average','trimf',[10 15 20]);
a=addmf(a,'output',1,'generous','trimf',[20 25 30]);
ruleList=[ ...
1 1 1 1 2
2 0 2 1 1
3 2 3 1 2 ];
a=addrule(a,ruleList);
2-81
Tutorial
FIS Evaluation
To evaluate the output of a fuzzy system for a given input, use the function
evalfis. For example, the following script evaluates tipper at the input,
[1 2].
a = readfis('tipper');
evalfis([1 2], a)
ans =
5.5586
This function can also be used for multiple collections of inputs, because
different input vectors are represented in different parts of the input
structure.
evalfis([3 5; 2 7], a)
ans =
12.2184
7.7885
2-82
All the information for a given fuzzy inference system is contained in the FIS
structure, including variable names, membership function definitions, and
so on. This structure can itself be thought of as a hierarchy of structures,
as shown in the following diagram.
You can generate a listing of information on the FIS using the showfis
command, as shown in the following code sample:
showfis(a)
1. Name
2. Type
3. Inputs/Outputs
4. NumInputMFs
5. NumOutputMFs
6. NumRules
7. AndMethod
8. OrMethod
9. ImpMethod
10. AggMethod
11. DefuzzMethod
12. InLabels
tipper
mamdani
[ 2 1 ]
[ 3 2 ]
3
3
min
max
min
max
centroid
service
2-83
Tutorial
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
42.
43.
44.
42.
43.
44.
42.
43.
2-84
OutLabels
InRange
OutRange
InMFLabels
OutMFLabels
InMFTypes
OutMFTypes
InMFParams
OutMFParams
Rule Antecedent
Rule Consequent
Rule Weight
Rule Connection
food
tip
[ 0 10 ]
[ 0 10 ]
[ 0 30 ]
poor
good
excellent
rancid
delicious
cheap
average
generous
gaussmf
gaussmf
gaussmf
trapmf
trapmf
trimf
trimf
trimf
[ 1.5 0 0 0 ]
[ 1.5 5 0 0 ]
[ 1.5 10 0 0 ]
[ 0 0 1 3 ]
[ 7 9 10 10 ]
[ 0 5 10 0 ]
[ 10 15 20 0 ]
[ 20 25 30 0 ]
[ 1 1 ]
[ 2 0 ]
[ 3 2 ]
1
2
3
1
1
1
2
1
44.
2-85
Tutorial
Name='food'
Range=[0 10]
NumMFs=2
MF1='rancid':'trapmf',[0 0 1 3]
MF2='delicious':'trapmf',[7 9 10 10]
[Output1]
Name='tip'
Range=[0 30]
NumMFs=3
MF1='cheap':'trimf',[0 5 10]
MF2='average':'trimf',[10 15 20]
MF3='generous':'trimf',[20 25 30]
[Rules]
1 1, 1 (1) : 2
2 0, 2 (1) : 1
3 2, 3 (1) : 2
2-86
A controller for the water level in the tank needs to know the current water
level and it needs to be able to set the valve. Your controllers input is the
water level error (desired water level minus actual water level), and its output
is the rate at which the valve is opening or closing. A first pass at writing a
fuzzy controller for this system might be the following:
1. If (level is okay) then (valve is no_change) (1)
2. If (level is low) then (valve is open_fast) (1)
3. If (level is high) then (valve is close_fast) (1)
2-87
Tutorial
You can take fuzzy systems directly into Simulink and test them out in a
simulation environment. A Simulink block diagram for this system is shown
in the following figure. It contains a Simulink block called the Fuzzy Logic
Controller block. The Simulink block diagram for this system is sltank.
Typing
sltank
at the command line, causes the system to appear. At the same time, the file
tank.fis is loaded into the FIS structure tank.
Some experimentation shows that three rules are not sufficient, because the
water level tends to oscillate around the desired level. See the following plot:
2-88
2
1.8
1.6
1.4
1.2
1
0.8
0.6
0.4
0.2
0
0
10
20
30
40
50
60
Time (second)
70
80
90
100
You need to add another input, the water levels rate of change, to slow down
the valve movement when it gets close to the right level.
4. If (level is good) and (rate is negative), then (valve is close_slow) (1)
5. If (level is good) and (rate is positive), then (valve is open_slow) (1)
The demo, sltank is built with these five rules. With all five rules in
operations, you can examine the step response by simulating this system.
You do so by clicking Start from the pull-down menu under Simulate, and
clicking the Comparison block. The result looks similar to the following plot.
2-89
Tutorial
2
1.8
1.6
1.4
1.2
1
0.8
0.6
0.4
0.2
0
0
10
20
30
40
50
60
Time (second)
70
80
90
100
One interesting feature of the water tank system is that the tank empties
much more slowly than it fills up because of the specific value of the outflow
diameter pipe. You can deal with this by setting the close_slow valve
membership function to be slightly different from the open_slow setting.
A PID controller does not have this capability. The valve command versus
the water level change rate (depicted as water) and the relative water level
change (depicted as level) surface looks like this. If you look closely, you can
see a slight asymmetry to the plot.
2-90
0.8
0.6
0.4
valve
0.2
0
0.2
0.4
0.6
0.8
0.5
0.1
0.05
0
0.5
0.05
water
0.1
level
This demo contains a block called the Fuzzy Controller With Rule Viewer
block.
In this demo, the Rule Viewer opens when you start the simulation. This Rule
Viewer provides an animation of how the rules are fired during the water
tank simulation. The windows that open when you simulate the sltankrule
demo are depicted as follows.
2-91
Tutorial
The Rule Viewer that opens during the simulation can be used to access the
Membership Function Editor, the Rule Editor, or any of the other GUIs, (see
The Membership Function Editor on page 2-40, or The Rule Editor on page
2-50, for more information).
For example, you may want to open the Rule Editor to change one of your
rules. To do so, select Rules under the Edit menu of the open Rule Viewer.
Now, you can view or edit the rules for this Simulink model.
2-92
If you stop the simulation prior to selecting any of these editors, you should
change your FIS. Remember to save any changes you make to your FIS to the
workspace before you restart the simulation.
2-93
Tutorial
The Fuzzy Logic Toolbox library contains the Fuzzy Logic Controller
and Fuzzy Logic Controller with Rule Viewer blocks. It also includes a
Membership Functions sublibrary that contains Simulink blocks for the
built-in membership functions.
To add a block from the library, drag the block into the Simulink model
window. You can get help on a specific block by clicking Help.
2-94
FIS. This automatic model generation ability is called the Fuzzy Wizard.
The block diagram representation only uses built-in Simulink blocks and,
therefore, allows for efficient code generation. For more information about the
Fuzzy Logic Controller block, see the fuzblock reference page.
The Fuzzy Wizard cannot handle FIS with custom membership functions or
with AND, OR, IMP, and AGG functions outside of the following list:
orMethod:
max
andMethod: min,prod
impMethod: min,prod
aggMethod: max
In these cases, the Fuzzy Logic Controller block uses the S-function sffis to
simulate the FIS. For more information, see the sffis reference page.
2-95
Tutorial
If you are using the Fuzzy Logic Controller with Ruleviewer block, enter the
name of the structure variable or the name of the .fis file in FIS matrix.
Note When entering the name of the .fis file in the blocks, you must
enclose it in single quotes.
2-96
Type
slcp
Right-click on the Fuzzy Logic Controller block, and select Look under mask
from the right-click menu. The following subsystem opens.
2-97
Tutorial
Follow the same procedure to look under the mask of the FIS Wizard
subsystem to see the implementation of your FIS. This following figure
shows part of the implementation (the entire model is too large to show in
this document).
2-98
As the figure shows, the Fuzzy Logic Controller block uses built-in Simulink
blocks to implement your FIS. Although the models can grow complex, this
representation is better suited than the S-function sffis for efficient code
generation.
2-99
Tutorial
2-100
The final output of the system is the weighted average of all rule outputs,
computed as
N
wi zi
Final Output =
i=1
N
wi
i=1
2-101
Tutorial
1.
poor
3. Apply
implication
method (prod).
2. Apply
fuzzy
operation
(OR = max)
1. Fuzzify inputs
rancid
z 1 (cheap)
If
service is poor
or
2.
good
If
3.
food is rancid
z1
then
tip = cheap
then
tip = average
then
tip = generous
rule 2 has
no dependency
on input 2
z 2 (average)
service is good
excellent
delicious
z 3 (generous)
If
z2
service is excellent or
service = 3
input 1
food is delicious
z3
food = 8
input 2
output
tip = 16.3%
The preceding figure shows the fuzzy tipping model developed in previous
sections of this manual adapted for use as a Sugeno system. Fortunately, it is
frequently the case that singleton output functions are completely sufficient
for the needs of a given problem. As an example, the system tippersg.fis is
2-102
tip
20
15
10
10
8
10
6
8
6
2
food
2
0
service
The easiest way to visualize first-order Sugeno systems is to think of each rule
as defining the location of a moving singleton. That is, the singleton output
spikes can move around in a linear fashion in the output space, depending
on what the input is. This also tends to make the system notation very
compact and efficient. Higher-order Sugeno fuzzy models are possible, but
they introduce significant complexity with little obvious merit. Sugeno fuzzy
models whose output membership functions are greater than first order are
not supported by Fuzzy Logic Toolbox software.
Because of the linear dependence of each rule on the input variables, the
Sugeno method is ideal for acting as an interpolating supervisor of multiple
linear controllers that are to be applied, respectively, to different operating
conditions of a dynamic nonlinear system. For example, the performance
2-103
Tutorial
2-104
The function plotmf shows us that the membership function low generally
refers to input values less than zero, while high refers to values greater
than zero. The function gensurf shows how the overall fuzzy system output
switches smoothly from the line called line1 to the line called line2.
subplot(2,1,1), plotmf(fismat,'input',1)
subplot(2,1,2),gensurf(fismat)
low
high
Degree of belief
0.8
0.6
0.4
0.2
0
5
0
input
0
input
output
3
2
1
0
1
5
2-105
Tutorial
2-106
Introduction
The basic structure of the type of fuzzy inference system seen thus far is a
model that maps input characteristics to input membership functions, input
membership function to rules, rules to a set of output characteristics, output
characteristics to output membership functions, and the output membership
function to a single-valued output or a decision associated with the output.
You have considered only fixed membership functions that were chosen
arbitrarily. You have applied fuzzy inference to only modeling systems whose
rule structure is essentially predetermined by the users interpretation of the
characteristics of the variables in the model.
In this section we discuss the use of the function anfis and the ANFIS
Editor GUI in the toolbox. These tools apply fuzzy inference techniques to
data modeling. As you have seen from the other fuzzy inference GUIs, the
2-107
Tutorial
A Modeling Scenario
Suppose you want to apply fuzzy inference to a system for which you already
have a collection of input/output data that you would like to use for modeling,
model-following, or some similar scenario. You do not necessarily have a
predetermined model structure based on characteristics of variables in your
system.
In some modeling situations, you cannot discern what the membership
functions should look like simply from looking at data. Rather than choosing
the parameters associated with a given membership function arbitrarily,
these parameters could be chosen so as to tailor the membership functions
to the input/output data in order to account for these types of variations
in the data values. In such cases, you can use the Fuzzy Logic Toolbox
neuro-adaptive learning techniques incorporated in the anfis command.
What Is ANFIS?
The acronym ANFIS derives its name from adaptive neuro-fuzzy inference
system. Using a given input/output data set, the toolbox function anfis
2-108
2-109
Tutorial
2-110
different than the applied checking data set. By examining the checking error
sequence over the training period, it is clear that the checking data set is not
good for model validation purposes. This example illustrates the use of the
ANFIS Editor GUI to compare data sets.
Constraints of anfis
anfis is much more complex than the fuzzy inference systems discussed
so far, and is not available for all of the fuzzy inference system options.
Specifically, anfis only supports Sugeno-type systems, and these must have
the following properties:
2-111
Tutorial
The ANFIS Editor GUI window shown in the following figure includes four
distinct areas to support a typical workflow. The GUI lets you perform the
following tasks:
1 Loading, Plotting, and Clearing the Data on page 2-113
2 Generating or Loading the Initial FIS Structure on page 2-113
3 Training the FIS on page 2-114
4 Validating the Trained FIS on page 2-115
Access the online help topics by clicking Help in the ANFIS Editor.
2-112
After you load the data, it displays in the plot. The training, testing and
checking data are annotated in blue as circles, diamonds, and pluses
respectively.
To clear a specific data set from the GUI:
1 In the Load data area, select the data Type.
2 Click Clear Data.
This action also removes the corresponding data from the plot.
2-113
Tutorial
method.
The optimization methods train the membership function parameters to
emulate the training data.
Note The hybrid optimization method is a combination of least-squares
and backpropagation gradient descent method.
2 Enter the number of training Epochs and the training Error Tolerance
2-114
This action adjusts the membership function parameters and displays the
error plots.
Examine the error plots to determine overfitting during the training. If
you notice the checking error increasing over iterations, it indicates model
overfitting. For examples on model overfitting, see ANFIS Editor GUI
Example 1: Checking Data Helps Model Validation on page 2-115 and
ANFIS Editor GUI Example 2: Checking Data Does Not Validate Model on
page 2-125.
This action plots the test data against the FIS output (shown in red) in
the plot.
For more information on the use of testing data and checking data for model
validation, see Model Validation Using Testing and Checking Data Sets on
page 2-110.
2-115
Tutorial
Loading Data
To work both of the following examples, you load the training data
sets (fuzex1trnData and fuzex2trnData) and the checking data sets
(fuzex1chkData and fuzex2chkData), into the ANFIS Editor GUI from the
workspace. You may also substitute your own data sets.
To load the data sets from the workspace into the ANFIS Editor GUI:
1 Type the following commands at the MATLAB command line to load the
data sets from the directory fuzzydemos into the MATLAB workspace:
load
load
load
load
fuzex1trnData.dat
fuzex2trnData.dat
fuzex1chkData.dat
fuzex2chkData.dat
command line.
3 To load the training data set from the workspace:
a
In the Load data portion of the GUI, select the following options:
Type: Training
From: worksp.
b Click Load Data to open the Load from workspace dialog box.
2-116
The training data set is used to train a fuzzy system by adjusting the
membership function parameters that best model this data, and appears
in the plot in the center of the GUI as a set of circles.
The horizontal axis is marked data set index. This index indicates the
row from which that input data value was obtained (whether or not
the input is a vector or a scalar).
4 To load the checking data set from the workspace:
a In the Load data portion of the GUI, select Checking in the Type
column.
b Click Load Data to open the Load from workspace dialog box.
2-117
Tutorial
The next step is to specify an initial fuzzy inference system for anfis
to train.
2-118
from which you can choose the number of membership functions, MFs, and
the type of input and output membership functions. There are only two
choices for the output membership function: constant and linear. This
limitation of output membership function choices is because anfis only
operates on Sugeno-type systems.
3 Fill in the entries as shown in the following figure, and click OK.
2-119
Tutorial
You can also implement this FIS generation from the command line using
the command genfis1 (for grid partitioning) or genfis2 (for subtractive
clustering).
will be disabled for anfis). The output membership functions must either
be all constant or all linear. For carrying out this and the following step,
see The FIS Editor on page 2-35 and The Membership Function Editor
on page 2-40.
3 Select the Rules menu item in the Edit menu, and use the Rule Editor to
portion of the GUI, click Load from worksp. or Load from file. You load
your FIS from a file if you have saved a FIS previously that you would like
to use. Otherwise you load your FIS from the workspace.
2-120
The branches in this graph are color coded. Color coding of branches
characterize the rules and indicate whether or not and, not, or or are used in
the rules. The input is represented by the left-most node and the output by
the right-most node. The node represents a normalization factor for the rules.
Clicking on the nodes indicates information about the structure.
You can view the membership functions or the rules by opening either the
Membership Function Editor, or the Rule Editor from the Edit menu.
2-121
Tutorial
ANFIS Training
The two anfis parameter optimization method options available for FIS
training are hybrid (the default, mixed least squares and backpropagation)
and backpropa (backpropagation). Error Tolerance is used to create a
training stopping criterion, which is related to the error size. The training
will stop after the training data error remains within this tolerance. This is
best left set to 0 if you are unsure how your training error may behave.
Note If you want to save the training error data generated during ANFIS
training to the MATLAB workspace, you must train the FIS at the command
line. For an example, Example Saving Training Error Data to the
MATLAB Workspace on page 2-135.
To start the training:
1 Leave the optimization method at hybrid.
2 Set the number of training epochs to 40, under the Epochs listing on the
2-122
The plot shows the checking error as on the top . The training error
appears as * * on the bottom. The checking error decreases up to a certain
point in the training, and then it increases. This increase represents the
point of model overfitting. anfis chooses the model parameters associated
with the minimum checking error (just prior to this jump point). This
example shows why the checking data option of anfis is useful.
2-123
Tutorial
2-124
Select the Checking option button in the Load data portion of the ANFIS
Editor GUI, and then click Clear Data to unload the checking data.
Close the ANFIS Editor GUI, and go to the MATLAB command line, and
retype anfisedit. In this case you must reload the training data.
After clearing the data, you must regenerate your FIS. After the FIS is
generated, you can use your first training experience to decide on the number
of training epochs you want for the second round of training.
and checking data) from the MATLAB workspace just as you did in the
previous example.
2-125
Tutorial
You should see a plot similar to the one in the following figure. The training
data appears as circles superimposed with the checking data, appearing as
pluses.
Train the FIS for this system exactly as you did in the previous example,
except now choose 60 Epochs before training. You should get the following
plot, showing the checking error as on top and the training error as *
* on the bottom.
2-126
In this case, the checking error is quite large. It appears that the minimum
checking error occurs within the first epoch. Using the checking data option
with anfis automatically sets the FIS parameters to be those associated with
the minimum checking error. Clearly this set of membership functions is not
the best choice for modeling the training data.
This example illustrates the problem discussed earlier wherein the checking
data set presented to anfis for training was sufficiently different from the
training data set. As a result, the trained FIS did not capture the features
of this data set very well. It is important to know the features of your data
set well when you select your training and checking data. When you do not
know the features of your data, you can analyze the checking error plots to
see whether or not the checking data performed sufficiently well with the
trained model.
2-127
Tutorial
In this example, the checking error is sufficiently large to indicate that either
you need to select more data for training or modify your membership function
choices (both the number of membership functions and the type). Otherwise,
the system can be retrained without the checking data, if you think the
training data sufficiently captures the features you are trying to represent.
To complete this example, test the trained FIS model against the checking
data. To do so, select Checking data in the Test FIS portion of the GUI, and
click Test Now. The following plot in the GUI indicates that there is quite a
discrepancy between the checking data output and the FIS output.
2-128
x ( t ) =
0 .2 x ( t )
1 + x10 ( t )
0 .1 x ( t )
This time series is chaotic, and so there is no clearly defined period. The
series does not converge or diverge, and the trajectory is highly sensitive to
initial conditions. This benchmark problem is used in the neural network and
fuzzy modeling research communities.
To obtain the time series value at integer points, we applied the fourth-order
Runge-Kutta method to find the numerical solution to the previous MG
equation; the result was saved in the file mgdata.dat. Assume x(0) = 1.2, =
17, and x(t) = 0 for time < 0. To plot the MG time series, type
load mgdata.dat
time = mgdata(:, 1); x = mgdata(:, 2);
figure(1), plot(time, x);
title('Mackey-Glass Chaotic Time Series')
xlabel('Time (sec)')
2-129
Tutorial
In time-series prediction, you need to use known values of the time series
up to the point in time, say, t, to predict the value at some point in the
future, say, t+P. The standard method for this type of prediction is to create
a mapping from D sample data points, sampled every units in time,
(x(t-(D-1)),..., x(t-), x(t)), to a predicted future value x(t+P). Following the
conventional settings for predicting the MG time series, set D = 4 and = P =
6. For each t, the input training data for anfis is a four-dimensional vector
of the following form.
w(t) = [x(t-18) x(t-12) x(t-6) x(t)]
The output training data corresponds to the trajectory prediction.
s(t) = x(t+6)
For each t, ranging in values from 118 to 1117, the training input/output
data is a structure whose first component is the four-dimensional input w,
and whose second component is the output s. There is 1000 input/output
2-130
data values. You use the first 500 data values for the anfis training (these
become the training data set), while the others are used as checking data for
validating the identified fuzzy model. This division of data values results in
two 500-point data structures, trnData and chkData.
The following code generates this data:
for t=118:1117,
Data(t-117,:)=[x(t-18) x(t-12) x(t-6) x(t) x(t+6)];
end
trnData=Data(1:500, :);
chkData=Data(501:end, :);
To start the training, you need a FIS structure that specifies the structure
and initial parameters of the FIS for learning. The genfis1 function handles
this specification.
fismat = genfis1(trnData);
Because you did not specify numbers and types of membership functions
used in the FIS, default values are assumed. These defaults provide two
generalized bell membership functions on each of the four inputs, eight
altogether. The generated FIS structure contains 16 fuzzy rules with 104
parameters. To achieve good generalization capability, it is important that
the number of training data points be several times larger than the number
parameters being estimated. In this case, the ratio between data and
parameters is about five (500/104).
The function genfis1 generates initial membership functions that are equally
spaced and cover the whole input space. You can plot the input membership
functions using the following commands.
figure(2)
subplot(2,2,1)
plotmf(fismat,
subplot(2,2,2)
plotmf(fismat,
subplot(2,2,3)
plotmf(fismat,
subplot(2,2,4)
plotmf(fismat,
'input', 1)
'input', 2)
'input', 3)
'input', 4)
2-131
Tutorial
Because the checking data option of anfis is invoked, the final FIS you choose
is the one associated with the minimum checking error. This result is stored
in fismat2. The following code plots these new membership functions.
figure(3)
subplot(2,2,1)
plotmf(fismat2, 'input', 1)
subplot(2,2,2)
plotmf(fismat2, 'input', 2)
subplot(2,2,3)
plotmf(fismat2, 'input', 3)
2-132
subplot(2,2,4)
plotmf(fismat2, 'input', 4)
2-133
Tutorial
The plots display the root-mean-square error. The plot in blue represents
error1, the error for training data . The plot in green represents error2,
the error for checking data .
In addition to these error plots, you may want to plot the FIS output versus
the training or checking data. To compare the original MG time series and
the fuzzy prediction side by side, try
figure(5)
anfis_output = evalfis([trnData(:,1:4); chkData(:,1:4)], ...
fismat2);
index = 125:1124;
subplot(211), plot(time(index), [x(index) anfis_output]);
xlabel('Time (sec)');
title('MG Time Series and ANFIS Prediction');
subplot(212), plot(time(index), x(index) - anfis_output);
xlabel('Time (sec)');
title('Prediction Errors');
2-134
The difference between the original MG time series and the values estimated
using anfis is very small, Thus, you can only see one curve in the first plot.
The prediction error appears in the second plot with a much finer scale. You
trained for only 10 epochs. If you apply more extensive training, you get
better performance.
2-135
Tutorial
load fuzex1trnData.dat
load fuzex1chkData.dat
2 Open the ANFIS Editor GUI by typing the following command:
anfisedit
3 Load the training data from the MATLAB workspace into the ANFIS
Editor GUI:
a In the Load data panel of the ANFIS Editor, verify that Training is
2-136
The ANFIS Editor displays the training data in the plot as a set of
circles ().
4 Load the checking data from the MATLAB workspace into the ANFIS
Editor GUI:
a In the Load data panel of the ANFIS Editor, select Checking in the
Type column.
2-137
Tutorial
b Click Load Data to open the Load from workspace dialog box.
c Type fuzex1chkData as the variable name, and click OK.
The ANFIS Editor displays the checking data as plus signs (+)
superimposed on the training data.
selected.
b Click Generate FIS.
This action opens a dialog box where you specify the structure of the FIS.
2-138
2-139
Tutorial
This action opens a dialog box where you specify the MATLAB variable
name.
2-140
MATLAB prompt:
figure;hold on;
fismat=initfis;
for ct=1:40,
[fismat,error]=anfis(fuzex1trnData,fismat,2,NaN,fuzex1chkData,1);
plot(ct,error(1),'b*');
end
To improve accuracy when you train the FIS, the code uses the results
of the current iteration returned by the anfis command as the initial
conditions for the next iteration. The output argument error contains the
root mean squared errors representing the training data error. For more
information, see the anfis reference page.
2-141
Tutorial
The plot of the training error versus the number of epochs appears in the
next figure.
2-142
When the ANFIS Editor GUI is invoked using anfisedit, only the training
data set must exist prior to implementing anfis. In addition, the step-size is
fixed when the adaptive neuro-fuzzy system is trained using this GUI tool.
Training Data
The training data, trnData, is a required argument to anfis, as well as
to the ANFIS Editor GUI. Each row of trnData is a desired input/output
pair of the target system you want to model Each row starts with an input
vector and is followed by an output value. Therefore, the number of rows of
trnData is equal to the number of training data pairs, and, because there is
only one output, the number of columns of trnData is equal to the number of
inputs plus one.
2-143
Tutorial
Training Options
The ANFIS Editor GUI tool allows you to choose your desired error tolerance
and number of training epochs.
Training option trnOpt for the command line anfis is a vector that specifies
the stopping criteria and the step-size adaptation strategy:
trnOpt(1): number of training epochs, default = 10
trnOpt(2): error tolerance, default = 0
trnOpt(3): initial step-size, default = 0.01
trnOpt(4): step-size decrease rate, default = 0.9
trnOpt(5): step-size increase rate, default = 1.1
If any element of trnOpt is an NaN or missing, then the default value is taken.
The training process stops if the designated epoch number is reached or the
error goal is achieved, whichever comes first.
2-144
Usually, the step-size profile is a curve that increases initially, reaches some
maximum, and then decreases for the remainder of the training. You achieve
this ideal step-size profile by adjusting the initial step-size and the increase
and decrease rates (trnOpt(3) - trnOpt(5)). The default values are set up
to cover a wide range of learning tasks. For any specific application, you
may want to modify these step-size options in order to optimize the training.
However, there are no user-specified step-size options for training the adaptive
neuro-fuzzy inference system generated using the ANFIS Editor GUI.
Display Options
Display options apply only to the command-line function anfis.
For the command line anfis, the display options argument, dispOpt, is a
vector of either 1s or 0s that specifies what information to display, (print
in the MATLAB command window), before, during, and after the training
process. A 1 is used to denote print this option, whereas a 0 denotes do not
print this option:
dispOpt(1): display ANFIS information, default = 1
dispOpt(2): display error (each epoch), default = 1
dispOpt(3): display step-size (each epoch), default = 1
dispOpt(4): display final results, default = 1
The default mode displays all available information. If any element of
dispOpt is NaN or missing, the default value is used.
Method
Both the ANFIS Editor GUI and the command line anfis apply either
a backpropagation form of the steepest descent method for membership
function parameter estimation, or a combination of backpropagation and the
least-squares method to estimate membership function parameters. The
choices for this argument are hybrid or backpropagation. These method
choices are designated in the command line function, anfis, by 1 and 0,
respectively.
2-145
Tutorial
error. This FIS structure is the one that you use to represent the fuzzy system
when there is no checking data used for model cross-validation. This data also
represents the FIS structure that is saved by the ANFIS Editor GUI when
the checking data option is not used.
When you use the checking data option, the output saved is that associated
with the minimum checking error.
Training Error
The training error is the difference between the training data output value,
and the output of the fuzzy inference system corresponding to the same
training data input value, (the one associated with that training data output
value). The training error trnError records the root mean squared error
(RMSE) of the training data set at each epoch. fismat1 is the snapshot
of the FIS structure when the training error measure is at its minimum.
The ANFIS Editor GUI plots the training error versus epochs curve as the
system is trained.
Step-Size
You cannot control the step-size options with the ANFIS Editor GUI. Using
the command line anfis, the step-size array ss records the step-size during
the training. Plotting ss gives the step-size profile, which serves as a
reference for adjusting the initial step-size and the corresponding decrease
and increase rates. The step-size (ss) for the command-line function anfis
is updated according to the following guidelines:
If the error undergoes four consecutive reductions, increase the step-size by
multiplying it by a constant (ssinc) greater than one.
If the error undergoes two consecutive combinations of one increase and
one reduction, decrease the step-size by multiplying it by a constant
(ssdec) less than one.
The default value for the initial step-size is 0.01; the default values for ssinc
and ssdec are 1.1 and 0.9, respectively. All the default values can be changed
via the training option for the command line anfis.
2-146
Checking Data
The checking data, chkData, is used for testing the generalization capability
of the fuzzy inference system at each epoch. The checking data has the same
format as that of the training data, and its elements are generally distinct
from those of the training data.
The checking data is important for learning tasks for which the input number
is large, and/or the data itself is noisy. A fuzzy inference system needs to
track a given input/output data set well. Because the model structure used
for anfis is fixed, there is a tendency for the model to overfit the data
on which is it trained, especially for a large number of training epochs. If
overfitting does occur, the fuzzy inference system may not respond well to
other independent data sets, especially if they are corrupted by noise. A
validation or checking data set can be useful for these situations. This data
set is used to cross-validate the fuzzy inference model. This cross-validation
requires applying the checking data to the model and then seeing how well
the model responds to this data.
When the checking data option is used with anfis, either via the command
line, or using the ANFIS Editor GUI, the checking data is applied to the
model at each training epoch. When the command line anfis is invoked,
the model parameters that correspond to the minimum checking error are
returned via the output argument fismat2. The FIS membership function
parameters computed using the ANFIS Editor GUI when both training and
checking data are loaded are associated with the training epoch that has
a minimum checking error.
The use of the minimum checking data error epoch to set the membership
function parameters assumes
The checking data is similar enough to the training data that the checking
data error decreases as the training begins.
The checking data increases at some point in the training after the data
overfitting occurs.
Depending on the behavior of the checking data error, the resulting FIS may
or may not be the one you need to use. Refer to ANFIS Editor GUI Example
2: Checking Data Does Not Validate Model on page 2-125.
2-147
Tutorial
Checking Error
The checking error is the difference between the checking data output value,
and the output of the fuzzy inference system corresponding to the same
checking data input value, which is the one associated with that checking
data output value. The checking error chkError records the RMSE for the
checking data at each epoch. fismat2 is the snapshot of the FIS structure
when the checking error is at its minimum. The ANFIS Editor GUI plots the
checking error versus epochs curve as the system is trained.
2-148
Fuzzy Clustering
Fuzzy Clustering
In this section...
What is Data Clustering on page 2-149
Fuzzy C-Means Clustering on page 2-149
Subtractive Clustering on page 2-155
Data Clustering Using the Clustering GUI Tool on page 2-167
2-149
Tutorial
2-150
Fuzzy Clustering
Next, invoke the command-line function fcm to find two clusters in this data
set until the objective function is no longer decreasing much at all.
[center,U,objFcn] = fcm(fcmdata,2);
2-151
Tutorial
Here, the variable center contains the coordinates of the two cluster centers,
U contains the membership grades for each of the data points, and objFcn
contains a history of the objective function across the iterations.
This command returns the following result:
Iteration count = 1, obj. fcn = 8.794048
Iteration count = 2, obj. fcn = 6.986628
.....
Iteration count = 12, obj. fcn = 3.797430
The fcm function is an iteration loop built on top of the following routines:
initfcm initializes the problem
distfcm performs Euclidean distance calculation
stepfcm performs one iteration of clustering
2-152
Fuzzy Clustering
To view the progress of the clustering, plot the objective function by typing
the following commands:
figure
plot(objFcn)
title('Objective Function Values')
xlabel('Iteration Count')
ylabel('Objective Function Value')
2-153
Tutorial
Finally, plot the two cluster centers found by the fcm function using the
following code:
maxU = max(U);
index1 = find(U(1, :) == maxU);
index2 = find(U(2, :) == maxU);
figure
line(fcmdata(index1, 1), fcmdata(index1, 2), 'linestyle',...
'none','marker', 'o','color','g');
line(fcmdata(index2,1),fcmdata(index2,2),'linestyle',...
'none','marker', 'x','color','r');
hold on
plot(center(1,1),center(1,2),'ko','markersize',15,'LineWidth',2)
plot(center(2,1),center(2,2),'kx','markersize',15,'LineWidth',2)
Note Every time you run this example, the fcm function initializes with
different initial conditions. This behavior swaps the order in which the cluster
centers are computed and plotted.
2-154
Fuzzy Clustering
Subtractive Clustering
If you do not have a clear idea how many clusters there should be for a
given set of data, Subtractive clustering, [2], is a fast, one-pass algorithm for
estimating the number of clusters and the cluster centers in a set of data. The
cluster estimates, which are obtained from the subclust function, can be
used to initialize iterative optimization-based clustering methods (fcm) and
model identification methods (like anfis). The subclust function finds the
clusters by using the subtractive clustering method.
2-155
Tutorial
The next figure displays the input and the output data.
2-156
Fuzzy Clustering
2-157
Tutorial
fismat=genfis2(datin,datout,0.5);
The genfis2 function is a fast, one-pass method that does not perform any
iterative optimization. A FIS structure is returned; the model type for the FIS
structure is a first order Sugeno model with three rules.
Use the following commands to verify the model. Here, trnRMSE is the root
mean square error of the system generated by the training data.
fuzout=evalfis(datin,fismat);
trnRMSE=norm(fuzout-datout)/sqrt(length(fuzout))
Next, apply the test data to the FIS to validate the model. In this example,
the checking data is used for both checking and testing the FIS parameters.
Here, chkRMSE is the root mean square error of the system generated by the
checking data.
chkfuzout=evalfis(chkdatin,fismat);
chkRMSE=norm(chkfuzout-chkdatout)/sqrt(length(chkfuzout))
2-158
Fuzzy Clustering
Use the following commands to plot the output of the model chkfuzout
against the checking data chkdatout.
figure
plot(chkdatout)
hold on
plot(chkfuzout,'o')
hold off
The model output and checking data are shown as circles and solid blue line,
respectively. The plot shows the model does not perform well on the checking
data.
2-159
Tutorial
At this point, you can use the optimization capability of anfis to improve the
model. First, try using a relatively short anfis training (20 epochs) without
implementing the checking data option, and then test the resulting FIS model
against the testing data. To perform the optimization, type the following
command:
fismat2=anfis([datin datout],fismat,[20 0 0.1]);
Here, 20 is the number of epochs, 0 is the training error goal, and 0.1 is the
initial step size.
This command returns the following result:
ANFIS info:
Number of nodes: 44
Number of linear parameters: 18
Number of nonlinear parameters: 30
Total number of parameters: 48
Number of training data pairs: 75
Number of checking data pairs: 0
Number of fuzzy rules: 3
Start training ANFIS ...
1
0.527607
.
.
20
0.420275
Designated epoch number reached --> ANFIS training completed at epoch 20.
After the training is done, validate the model by typing the following
commands:
fuzout2=evalfis(datin,fismat2);
trnRMSE2=norm(fuzout2-datout)/sqrt(length(fuzout2))
chkfuzout2=evalfis(chkdatin,fismat2);
chkRMSE2=norm(chkfuzout2-chkdatout)/sqrt(length(chkfuzout2))
2-160
Fuzzy Clustering
trnRMSE2 =
0.4203
chkRMSE2 =
0.5894
The model has improved a lot with respect to the training data, but only a little
with respect to the checking data. Plot the improved model output obtained
using anfis against the testing data by typing the following commands:
figure
plot(chkdatout)
hold on
plot(chkfuzout2,'o')
hold off
2-161
Tutorial
The model output and checking data are shown as circles and solid blue line,
respectively. This plot shows that genfis2 can be used as a stand-alone,
fast method for generating a fuzzy model from data, or as a preprocessor to
anfis for determining the initial rules. An important advantage of using a
clustering method to find rules is that the resultant rules are more tailored
to the input data than they are in a FIS generated without clustering. This
reduces the problem of an excessive propagation of rules when the input data
has a high dimension.
Overfitting
Overfitting can be detected when the checking error starts to increase while
the training error continues to decrease.
2-162
Fuzzy Clustering
To check the model for overfitting, use anfis with the checking data option to
train the model for 200 epochs. Here, fismat3 is the FIS structure when the
training error reaches a minimum. fismat4 is the snapshot FIS structure
taken when the checking data error reaches a minimum.
[fismat3,trnErr,stepSize,fismat4,chkErr]= ...
anfis([datin datout],fismat,[200 0 0.1],[], ...
[chkdatin chkdatout]);
After the training completes, validate the model by typing the following
commands:
fuzout4=evalfis(datin,fismat4);
trnRMSE4=norm(fuzout4-datout)/sqrt(length(fuzout4))
chkfuzout4=evalfis(chkdatin,fismat4);
chkRMSE4=norm(chkfuzout4-chkdatout)/sqrt(length(chkfuzout4))
The error with the training data is the lowest thus far, and the error with the
checking data is also slightly lower than before. This result suggests perhaps
there is an overfit of the system to the training data. Overfitting occurs when
2-163
Tutorial
you fit the fuzzy system to the training data so well that it no longer does a
very good job of fitting the checking data. The result is a loss of generality.
To view the improved model output, plot the model output against the
checking data by typing the following commands:
figure
plot(chkdatout)
hold on
plot(chkfuzout4,'o')
hold off
The model output and checking data are shown as circles and solid blue line,
respectively.
2-164
Fuzzy Clustering
Next, plot the training error trnErr by typing the following commands:
figure
plot(trnErr)
Title('Training Error')
xlabel('Number of Epochs')
ylabel('Training Error')
This plot shows that the training error settles at about the 60th epoch point.
2-165
Tutorial
The plot shows that the smallest value of the checking data error occurs at
the 52nd epoch, after which it increases slightly even as anfis continues to
minimize the error against the training data all the way to the 200th epoch.
Depending on the specified error tolerance, the plot also indicates the models
ability to generalize the test data.
2-166
Fuzzy Clustering
You can also compare the output of fismat2 and fistmat4 against the
checking data chkdatout by typing the following commands:
figure
plot(chkdatout)
hold on
plot(chkfuzout4,'ob')
plot(chkfuzout2,'+r')
2-167
Tutorial
2-168
Fuzzy Clustering
Access the online help topics by clicking Info or using the Help menu in
the Clustering GUI.
Methods.
2 Set options for the selected method using the Influence Range, Squash,
2-169
Tutorial
2-170
2-171
Tutorial
The fis.c file contains all the necessary functions to perform the fuzzy
inference process:
This file provides the 11 Fuzzy Logic Toolbox membership functions with
their default settings.
You can add a new membership function or new reasoning mechanism
by updating the fis.c file.
The fismain executable code, generated after compiling the source codes,
reads an input data file and a FIS structure file to simulate the output. The
syntax for calling fismain is similar to its MEX-file counterpart evalfis,
except that all matrices are replaced with files. To learn more about evalfis,
see the evalfis function reference page.
matlabroot\toolbox\fuzzy\fuzzy.
Tip You can find the root directory of your MATLAB installation by typing
matlabroot at the MATLAB command prompt.
2 In the DOS Command Window, type the following command:
lcc -c fismain.c
2-172
Note You may encounter the following error when executing the lcc
command:
'lcc' is not recognized as an internal or external command,
operable program or batch file.
To learn how to troubleshoot this error, see the Including the lcc
Command in the PATH Environment Variable on page 2-175 section.
3 In the DOS Command Window, type the following command:
lcclnk fismain.obj.
To learn how to troubleshoot this error, see the Including the lcclnk
Command in the PATH Environment Variable on page 2-175 section.
4 Open MATLAB desktop, and change to your current working directory
data file:
[x, y] = meshgrid(-5:5, -5:5);
input_data = [x(:) y(:)];
save fis_in input_data -ascii
2-173
Tutorial
This command saves the input data as a 121-by-2 matrix in the fis_in
ASCII file in your current working directory. Each row of the matrix
represents an input vector.
6
working directory, and type the following command to call the stand-alone
executable code:
fismain fis_in mam21.fis
This command uses the data file fis_in and the FIS structure file
mam21.fis, and generates 121 outputs on your screen.
Tip You can also direct the outputs to a file using the following command
in the DOS Command Window:
fismain fis_in mam21.fis > fis_out
This command saves the output data fis_out as a 121-by-1 matrix in your
current working directory. Each row of the output matrix represents an
output vector.
2-174
9 To verify that the fuzzy inference engine output matches the MATLAB
The difference results from the relative precision between the outputs.
To include the command in the PATH environment variable, type the following
in the DOS Command Window:
matlabroot\sys\lcc\bin\lcc -Imatlabroot\sys\lcc\include fismain.c
Press Enter when prompted to Please enter the path for the
<include> header files.
2-175
Tutorial
To include the command in the PATH environment variable, type the following
in the DOS Command Window:
matlabroot\sys\lcc\bin\lcclnk fismain.obj
matlabroot\toolbox\fuzzy\fuzzy.
Tip You can find the root directory of your MATLAB installation by typing
matlabroot at the MATLAB command prompt.
2 In the UNIX Command Window, type the following command:
command:
[x, y] = meshgrid(-5:5, -5:5);
input_data = [x(:) y(:)];
save fis_in input_data -ascii
2-176
This command saves the input data as a 121-by-2 matrix in the ASCII
file fis_in in your current working directory. Each row of the matrix
represents an input vector.
Tip You can find your current working directory in the Current Directory
field in the MATLAB desktop toolbar.
4 Copy the FIS structure file mam21.fis from the
This command uses the data file fis_in and the FIS structure file
mam21.fis and generates 121 outputs on your screen.
Tip You can also direct the outputs to another file using the following
command in the DOS Command Window:
fismain fis_in mam21.fis > fis_out
This command saves the output data fis_out as a 121-by-1 matrix in your
current working directory. Each row of the output matrix represents an
output vector.
2-177
Tutorial
7 To verify that the fuzzy inference engine output matches the MATLAB
The difference results from the relative precision between the outputs.
2-178
3
Function Reference
GUI Tools and Plotting (p. 3-2)
Function Reference
3-2
anfisedit
findcluster
fuzzy
mfedit
plotfis
plotmf
ruleedit
ruleview
surfview
Membership Functions
Membership Functions
dsigmf
gauss2mf
gaussmf
gbellmf
pimf
psigmf
sigmf
smf
trapmf
Trapezoidal-shaped built-in
membership function
trimf
Triangular-shaped built-in
membership function
zmf
3-3
Function Reference
3-4
addmf
addrule
addvar
defuzz
evalfis
evalmf
gensurf
getfis
mf2mf
newfis
parsrule
readfis
rmmf
rmvar
setfis
showfis
showrule
writefis
fcm
genfis1
genfis2
genfis3
subclust
3-5
Function Reference
Simulink Environment
3-6
fuzblock
sffis
4
Functions Alphabetical
List
addmf
Purpose
Syntax
a = addmf(a,'varType',varIndex,'mfName','mfType',mfParams)
Description
Examples
4-2
a = newfis('tipper');
a = addvar(a,'input','service',[0 10]);
a = addmf(a,'input',1,'poor','gaussmf',[1.5 0]);
a = addmf(a,'input',1,'good','gaussmf',[1.5 5]);
a = addmf(a,'input',1,'excellent','gaussmf',[1.5 10]);
plotmf(a,'input',1)
addmf
poor
good
excellent
Degree of belief
0.8
0.6
0.4
0.2
0
0
See Also
service
10
4-3
addrule
Purpose
Syntax
a = addrule(a,ruleList)
Description
Examples
ruleList=[
1 1 1 1 1
1 2 2 1 1];
a = addrule(a,ruleList);
If the system a has two inputs and one output, the first rule can be
interpreted as:
If Input 1 is MF 1 and Input 2 is MF 1, then Output 1 is MF 1.
See Also
4-4
addvar
Purpose
Syntax
a = addvar(a,'varType','varName',varBounds)
Description
Examples
a = newfis('tipper');
a = addvar(a,'input','service',[0 10]);
getfis(a,'input',1)
See Also
4-5
anfis
Purpose
Syntax
[fis,error,stepsize] = anfis(trnData)
[fis,error,stepsize] = anfis(trnData,initFis)
[fis,error,stepsize] = anfis(trnData,numMFs)
[fis,error,stepsize,chkFis,chkErr] = ...
anfis(trnData,initFis,trnOpt,dispOpt,chkData,optMethod)
[fis,error,stepsize,chkFis,chkErr] = ...
anfis(trnData,numMFs,trnOpt,dispOpt,chkData,optMethod)
Description
This syntax is the major training routine for Sugeno-type fuzzy inference
systems. anfis uses a hybrid learning algorithm to identify parameters
of Sugeno-type fuzzy inference systems. It applies a combination of
the least-squares method and the backpropagation gradient descent
method for training FIS membership function parameters to emulate a
given training data set. anfis can also be invoked using an optional
argument for model validation. The type of model validation that takes
place with this option is a checking for model overfitting, and the
argument is a data set called the checking data set.
The arguments in the description for anfis are as follows. Note
that you can specify the arguments trnOpt, dispOpt, chkData, and
optMethod as empty, [], when necessary:
trnData: the name of a training data set. This matrix contains data
input in all but the last column. The last column contains a single
vector of output data.
initFis: the name of a fuzzy inference system (FIS) used to provide
anfis with an initial set of membership functions for training.
Without this option, anfis uses genfis1 to implement a default
initial FIS for training. This default FIS has two membership
functions of the Gaussian type, when it is invoked with only one
argument. If initFis is provided as a single number (or a vector),
it is taken as the number of membership functions (or the vector)
whose entries are the respective numbers of membership functions
associated with each respective input when these numbers differ
for each input). In this case, both arguments of anfis are passed
4-6
anfis
4-7
anfis
4-8
anfis
Examples
x = (0:0.1:10)';
y = sin(2*x)./exp(x/5);
trnData = [x y];
numMFs = 5;
mfType = 'gbellmf';
epoch_n = 20;
in_fis = genfis1(trnData,numMFs,mfType);
out_fis = anfis(trnData,in_fis,20);
plot(x,y,x,evalfis(x,out_fis));
legend('Training Data','ANFIS Output');
References
See Also
anfisedit, genfis1
4-9
anfisedit
Purpose
Syntax
anfisedit('a')
anfisedit(a)
anfisedit
Description
Using anfisedit, you bring up the ANFIS Editor GUI from which you
can load a data set and train anfis. The ANFIS Editor GUI invoked
using anfisedit('a'), opens the ANFIS Editor GUI from which you
can implement anfis using a FIS structure stored as a file a.fis.
anfisedit(a) operates the same way for a FIS structure a, stored as a
Menu
Items
On the ANFIS Editor GUI, there is a menu bar that allows you to open
related GUI tools, open and save systems, and so on. The File menu is
the same as the one found on the FIS Editor. Refer to fuzzy for more
information:
Use the following Edit menu item:
Undo to undo the most recent change.
FIS properties to invoke the FIS Editor.
Membership functions to invoke the Membership Function Editor.
Rules to invoke the Rule Editor.
Use the following View menu items:
Rules to invoke the Rule Viewer.
Surface to invoke the Surface Viewer.
See Also
4-10
convertfis
Purpose
Syntax
fis_new=convertfis(fis_old)
Description
4-11
defuzz
Purpose
Syntax
out = defuzz(x,mf,type)
Description
Examples
4-12
x = -10:0.1:10;
mf = trapmf(x,[-10 -8 -4 7]);
xx = defuzz(x,mf,'centroid');
dsigmf
Purpose
Syntax
y = dsigmf(x,[a1 c1 a2 c2])
Description
f ( x; a, c ) =
1
1+ e
a( x c)
Examples
x=0:0.1:10;
y=dsigmf(x,[5 2 5 7]);
plot(x,y)
xlabel('dsigmf, P=[5 2 5 7]')
1
0.75
0.5
0.25
0
0
4
6
dsigmf, P = [5 2 5 7]
10
4-13
dsigmf
See Also
4-14
evalfis
Purpose
Syntax
output= evalfis(input,fismat)
output= evalfis(input,fismat, numPts)
[output, IRR, ORR, ARR]= evalfis(input,fismat)
[output, IRR, ORR, ARR]= evalfis(input,fismat,
numPts)
Description
4-15
evalfis
Examples
fismat = readfis('tipper');
out = evalfis([2 1; 4 9],fismat)
See Also
4-16
ruleview, gensurf
evalmf
Purpose
Syntax
y = evalmf(x,mfParams,mfType)
Description
Examples
x=0:0.1:10;
mfparams = [2 4 6];
mftype = 'gbellmf';
y=evalmf(x,mfparams,mftype);
plot(x,y)
xlabel('gbellmf, P=[2 4 6]')
1
0.75
0.5
0.25
0
0
See Also
4
6
gbellmf, P = [2 4 6]
10
4-17
fcm
Purpose
Syntax
[center,U,obj_fcn] = fcm(data,cluster_n)
Description
4-18
fcm
Examples
4-19
findcluster
Purpose
Syntax
findcluster findcluster('file.dat')
Description
4-20
findcluster
Examples
findcluster('clusterdemo.dat')
See Also
fcm, subclust
4-21
fuzarith
Purpose
Syntax
C = fuzarith(X, A, B, operator)
Description
Examples
4-22
point_n = 101;
% this determines MF's resolution
min_x = -20; max_x = 20; % universe is [min_x, max_x]
x = linspace(min_x, max_x, point_n)';
A = trapmf(x, [-10 -2 1 3]); % trapezoidal fuzzy set A
B = gaussmf(x, [2 5]); % Gaussian fuzzy set B
C1 = fuzarith(x, A, B, 'sum');
subplot(2,1,1);
plot(x, A, 'b--', x, B, 'm:', x, C1, 'c');
title('fuzzy addition A+B');
C2 = fuzarith(x, A, B, 'sub');
subplot(2,1,2);
plot(x, A, 'b--', x, B, 'm:', x, C2, 'c');
title('fuzzy subtraction A-B');
C3 = fuzarith(x, A, B, 'prod');
fuzblock
Purpose
Syntax
fuzblock
Description
See Also
sffis, ruleview
4-23
fuzzy
Purpose
Syntax
fuzzy
fuzzy(fismat)
Description
The FIS Editor GUI tool allows you to edit the highest level features
of the fuzzy inference system, such as the number of input and output
variables, the defuzzification method used, and so on. Refer to The FIS
Editor on page 2-35 for more information about how to use the GUIs
associated with fuzzy.
The FIS Editor is the high-level display for any fuzzy logic inference
system. It allows you to call the various other editors to operate on the
FIS. This interface allows convenient access to all other editors with an
emphasis on maximum flexibility for interaction with the fuzzy system.
4-24
fuzzy
The
Diagram
The diagram displayed at the top of the window shows the inputs,
outputs, and a central fuzzy rule processor. Click one of the variable
boxes to make the selected box the current variable. You should see the
box highlighted in red. Double-click one of the variables to bring up the
Membership Function Editor. Double-click the fuzzy rule processor to
bring up the Rule Editor. If a variable exists but is not mentioned in
the rule base, it is connected to the rule processor block with a dashed
rather than a solid line.
Menu
Items
The FIS Editor displays a menu bar that allows you to open related
GUI tools, open and save systems, and so on.
Under File select
New FIS > Mamdani to open a new Mamdani-style system with no
variables and no rules called Untitled.
New FIS > Sugeno to open a new Sugeno-style system with no
variables and no rules called Untitled.
Import > From workspace to load a system from a specified FIS
structure variable in the workspace.
Import > From file to load a system from a specified .fis file.
Export > To workspace. to save the system to a FIS structure
variable in the workspace.
Export > To file to save the current system to a .fis file.
Print to print what is displayed in the GUI.
Close to close the GUI.
Under Edit select
Undo to undo the most recent change.
Add variable > Input to add another input to the current system.
Add variable > Output to add another output to the current system.
Remove Selected Variable to delete a selected variable.
4-25
fuzzy
Inference
Method
Pop-up
Menus
Five pop-up menus are provided to change the functionality of the five
basic steps in the fuzzy implication process:
And method: Choose min, prod, or Custom, for a custom operation.
Or method: Choose max, probor (probabilistic or), or Custom, for a
custom operation.
Implication: Choose min, prod, or Custom, for a custom operation.
This selection is not available for Sugeno-style fuzzy inference.
Aggregation: Choose max, sum, probor, or Custom, for a custom
operation. This selection is not available for Sugeno-style fuzzy
inference.
Defuzzification: For Mamdani-style inference, choose centroid,
bisector, mom (middle of maximum), som (smallest of maximum),
lom (largest of maximum), or Custom, for a custom operation. For
Sugeno-style inference, choose between wtaver (weighted average)
or wtsum (weighted sum).
See Also
4-26
gauss2mf
Purpose
Syntax
Description
f ( x; , c ) =
( x c )
2
e 2
Examples
x = (0:0.1:10)';
y1 = gauss2mf(x, [2 4 1 8]);
y2 = gauss2mf(x, [2 5 1 7]);
y3 = gauss2mf(x, [2 6 1 6]);
y4 = gauss2mf(x, [2 7 1 5]);
y5 = gauss2mf(x, [2 8 1 4]);
plot(x, [y1 y2 y3 y4 y5]);
set(gcf, 'name', 'gauss2mf', 'numbertitle', 'off');
4-27
gauss2mf
See Also
4-28
gaussmf
Purpose
Syntax
y = gaussmf(x,[sig c])
Description
f ( x; , c ) =
( x c )
2
e 2
Examples
and c
and c listed in
x=0:0.1:10;
y=gaussmf(x,[2 5]);
plot(x,y)
xlabel('gaussmf, P=[2 5]')
1
0.75
0.5
0.25
0
0
See Also
4
6
gaussmf, P = [2 5]
10
4-29
gbellmf
Purpose
Syntax
y = gbellmf(x,params)
Description
f ( x; a, b, c ) =
1+
xc
a
2b
Examples
x=0:0.1:10;
y=gbellmf(x,[2 4 6]);
plot(x,y)
xlabel('gbellmf, P=[2 4 6]')
1
0.75
0.5
0.25
0
0
See Also
4-30
4
6
gbellmf, P = [2 4 6]
10
genfis1
Purpose
Syntax
fismat = genfis1(data)
fismat = genfis1(data,numMFs,inmftype,outmftype)
Description
4-31
genfis1
Examples
4-32
Inference Method
Default
AND
prod
OR
max
Implication
prod
Aggregation
max
Defuzzification
wtaver
genfis1
See Also
4-33
genfis2
Purpose
Syntax
fismat
fismat
fismat
fismat
Description
=
=
=
=
genfis2(Xin,Xout,radii)
genfis2(Xin,Xout,radii,xBounds)
genfis2(Xin,Xout,radii,xBounds,options)
genfis2(Xin,Xout,radii,xBounds,options,user_centers)
4-34
genfis2
Default
AND
prod
OR
probor
Implication
prod
Aggregation
max
Defuzzification
wtaver
4-35
genfis2
Examples
Example 1
The following example uses the genfis2 function with the minimum
number of arguments and generates a FIS with default values. In this
case, a range of influence of 0.5 is specified for all data dimensions.
Xin1 = 7*rand(50,1);
Xin2 = 20*rand(50,1)-10;
Xin = [Xin1 Xin2];
Xout = 5*rand(50,1);
fismat = genfis2(Xin,Xout,0.5);
showfis(fismat) displays the contents of each field of the structure
fismat.
4-36
genfis2
Example 2
The following example assumes the combined data dimension is 3.
Suppose Xin has two columns and Xout has one column, then 0.5 and
0.25 are the ranges of influence for each of the Xin data dimensions, and
0.3 is the range of influence for the Xout data dimension.
Xin1 = 7*rand(50,1);
Xin2 = 20*rand(50,1)-10;
Xin = [Xin1 Xin2];
Xout = 5*rand(50,1);
fismat = genfis2(Xin,Xout,[0.5 0.25 0.3])
4-37
genfis2
Example 3
The following example specifies how to normalize the data in Xin and
Xout into values in the range [0 1] for processing. Suppose Xin has two
columns and Xout has one column, then the data in the first column of
Xin are scaled from [-10 +10], the data in the second column of Xin are
scaled from [-5 +5], and the data in Xout are scaled from [0 20].
Xin1 = 7*rand(50,1);
Xin2 = 20*rand(50,1)-10;
Xin = [Xin1 Xin2];
Xout = 5*rand(50,1);
fismat = genfis2(Xin,Xout,0.5,[-10 -5 0; 10 5 20])
See Also
4-38
genfis3
Purpose
Syntax
fismat
fismat
fismat
fismat
Description
=
=
=
=
genfis3(Xin,Xout)
genfis3(Xin,Xout,type)
genfis3(Xin,Xout,type,cluster_n)
genfis3(Xin,Xout,type,cluster_n,fcmoptions)
4-39
genfis3
Examples
Inference Method
Default
AND
prod
OR
probor
Implication
prod
Aggregation
sum
Defuzzification
wtaver
Example 1
The following example uses the genfis3 function with the minimum
number of arguments and generates a FIS using default values.
Xin1 = 7*rand(50,1);
Xin2 = 20*rand(50,1)-10;
Xin = [Xin1 Xin2];
Xout = 5*rand(50,1);
fismat = genfis3(Xin,Xout);
showfis(fismat) displays the contents of each field of the structure
fismat.
4-40
genfis3
Example 2
The following example generates a Mamdani FIS with three clusters.
Xin1 = 7*rand(50,1);
Xin2 = 20*rand(50,1)-10;
Xin = [Xin1 Xin2];
Xout = 5*rand(50,1);
fismat = genfis3(Xin,Xout,'mamdani',3)
4-41
genfis3
Example 3
The following example specifies the type of FIS, the number of desired
clusters and FCM options.
Xin1 = 7*rand(50,1);
Xin2 = 20*rand(50,1)-10;
Xin = [Xin1 Xin2];
Xout = 5*rand(50,1);
fis = genfis3(Xin,Xout,'mamdani',3,[2,100,1e-5,1])
See Also
4-42
gensurf
Purpose
Syntax
gensurf(fis)
gensurf(fis,inputs,output)
gensurf(fis,inputs,output,grids)
gensurf(fis,inputs,output,grids,refinput)
gensurf(fis,inputs,output,grids,refinput,numofpoints)
[x,y,z]=gensurf(...)
Description
4-43
gensurf
Example 1
a = readfis('tipper');
gensurf(a)
25
tip
20
15
10
5
10
8
10
6
8
6
2
food
Example 2
2
0
service
See Also
4-44
evalfis, surfview
getfis
Purpose
Syntax
getfis(a)
getfis(a,'fisprop')
getfis(a, vartype, varindex)
getfis(a,'vartype',varindex,'varprop')
getfis(a,'vartype',varindex,'mf',mfindex)
getfis(a,'vartype',varindex,'mf',mfindex,'mfprop')
Description
This function provides the fundamental access for the FIS structure.
With this one function you can learn about every part of the fuzzy
inference system.
The arguments for getfis are as follows:
a: the name of a workspace variable FIS structure.
'fisprop': a string indicating the field you want to access. Possible
fields include:
'name'
'type'
'numinputs'
'numoutputs'
'numinputmfs'
'numoutputmfs'
'numrules'
'andmethod'
'ormethod'
'impmethod'
'aggmethod'
'defuzzmethod'
4-45
getfis
'inlabels'
'outlabels'
'inrange'
'outrange'
'inmfs'
'outmfs'
'inmflabels'
'outmflabels'
'inmftypes'
'outmftypes'
'inmfparams'
'outmfparams'
'rulelist'
'Name' or 'NumInputs'.
4-46
getfis
You can also access fuzzy system properties directly using MATLAB
syntax for structures (including dot notation). See the examples that
follow.
Examples
or
a.type
ans =
mamdani
4-47
getfis
getfis(a,'input',1)
Name = service
NumMFs = 3
MFLabels =
poor
good
excellent
Range = [0 10]
or
a.input(1)
ans =
name: 'service'
range: [0 10]
mf: [1x3 struct]
or
a.input(1).name
ans =
service
or
4-48
getfis
a.input(1).mf(2)
ans =
name: 'good'
type: 'gaussmf'
params: [1.5000 5]
or
a.input(1).mf(2).name
ans =
good
See Also
setfis, showfis
4-49
mam2sug
Purpose
Syntax
sug_fis=mam2sug(mam_fis)
Description
Examples
4-50
mam_fismat = readfis('mam22.fis');
sug_fismat = mam2sug(mam_fismat);
subplot(2,2,1); gensurf(mam_fismat,
title('Mamdani system (Output 1)');
subplot(2,2,2); gensurf(sug_fismat,
title('Sugeno system (Output 1)');
subplot(2,2,3); gensurf(mam_fismat,
title('Mamdani system (Output 2)');
subplot(2,2,4); gensurf(sug_fismat,
title('Sugeno system (Output 2)');
[1 2], 1);
[1 2], 1);
[1 2],2);
[1 2],2);
mf2mf
Purpose
Syntax
outParams = mf2mf(inParams,inType,outType)
Description
Caution
Occasionally this translation results in lost information, so that if the
output parameters are translated back into the original membership
function type, the transformed membership function does not look the
same as it did originally.
The input arguments for mf2mf are as follows:
inParams: the parameters of the membership function you are
transforming
inType: a string name for the type of membership function you are
transforming
outType: a string name for the new membership function you are
transforming to
Examples
x=0:0.1:5;
mfp1 = [1 2 3];
mfp2 = mf2mf(mfp1,'gbellmf','trimf');
plot(x,gbellmf(x,mfp1),x,trimf(x,mfp2))
4-51
mf2mf
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0
See Also
4-52
0.5
1.5
2.5
3.5
4.5
mfedit
Purpose
Syntax
mfedit('a')
mfedit(a)
mfedit
Description
For each membership function you can change the name, the type, and
the parameters. Eleven built-in membership functions are provided for
you to choose from, although of course you can always create your own
specialized versions. Refer to The Membership Function Editor on
page 2-40 for more information about how to use mfedit.
4-53
mfedit
Select the icon for the variable on the upper left side of the diagram
(under FIS Variables) to display its associated membership functions
in the plot region. Select membership functions by clicking once on
them or their labels.
Menu
Items
4-54
Membership
Function
Pop-up
Menu
There are 11 built-in membership functions to choose from, and you also
have the option of installing a customized membership function.
See Also
newfis
Purpose
Syntax
a=newfis(fisName,fisType,andMethod,orMethod,impMethod,
...
aggMethod,defuzzMethod)
Description
This function creates new FIS structures. newfis has up to seven input
arguments, and the output argument is a FIS structure. The seven
input arguments are as follows:
fisName is the string name of the FIS structure, fisName.fis you
create.
fisType is the type of FIS.
andMethod, orMethod, impMethod, aggMethod, and defuzzMethod,
respectively, provide the methods for AND, OR, implication,
aggregation, and defuzzification.
Examples
The following example shows what the defaults are for each of the
methods.
a=newfis('newsys');
getfis(a)
returns
Name = newsys
Type = mamdani
NumInputs = 0
InLabels =
NumOutputs = 0
OutLabels =
NumRules
0
AndMethod
min
OrMethod
max
ImpMethod
min
AggMethod
max
4-55
newfis
DefuzzMethod
ans =
[newsys]
See Also
4-56
readfis, writefis
centroid
parsrule
Purpose
Syntax
fis2 = parsrule(fis,txtRuleList)
fis2 = parsrule(fis,txtRuleList,ruleFormat)
fis2 = parsrule(fis,txtRuleList,ruleFormat,lang)
Description
This function parses the text that defines the rules (txtRuleList) for
a MATLAB workspace FIS variable, fis, and returns a FIS structure
with the appropriate rule list in place. If the original input FIS
structure, fis, has any rules initially, they are replaced in the new
structure, fis2.
Three different rule formats (indicated by ruleFormat) are supported:
'verbose', 'symbolic', and 'indexed'. The default format is
'verbose'. When the optional language argument, lang, is used, the
rules are parsed in verbose mode, assuming the key words are in the
language, lang. This language must be either 'english', 'francais',
or 'deutsch'. The key language words in English are if, then, is, AND,
OR, and NOT.
Examples
See Also
a = readfis('tipper');
ruleTxt = 'if service is poor then tip is generous';
a2 = parsrule(a,ruleTxt,'verbose');
showrule(a2)
ans =
1. If (service is poor) then (tip is generous) (1)
addrule, ruleedit, showrule
4-57
pimf
Purpose
Syntax
y = pimf(x,[a b c d])
Description
xa
0,
2
a+b
2 x a ,
a
x
b a
2
a+b
x b
xb
,
1 2
2
b- a
b xc
f ( x; a, b, c, d) =
1,
2
1 2 x c , c x c + d
2
d c
2
c+d
xd
x d
2 d - c ,
2
0,
x d
Examples
4-58
x=0:0.1:10;
y=pimf(x,[1 4 5 10]);
plot(x,y)
xlabel('pimf, P=[1 4 5 10]')
pimf
1
0.75
0.5
0.25
0
0
See Also
4
6
pimf, P = [1 4 5 10]
10
4-59
plotfis
Purpose
Syntax
plotfis(fismat)
Description
Examples
See Also
4-60
a = readfis('tipper');
plotfis(a)
evalmf, plotmf
plotmf
Purpose
Syntax
plotmf(fismat,varType,varIndex)
Description
This function plots all of the membership functions in the FIS called
fismat associated with a given variable whose type and index are
respectively given by varType (must be 'input' or 'output'), and
varIndex. This function can also be used with the MATLAB function,
subplot.
Examples
a = readfis('tipper');
plotmf(a,'input',1)
poor
good
excellent
Degree of belief
0.8
0.6
0.4
0.2
0
0
See Also
5
service
10
evalmf, plotfis
4-61
probor
Purpose
Probabilistic OR
Syntax
y = probor(x)
Description
Examples
4-62
x = (0:0.1:10);
figure('Name','Probabilistic OR','NumberTitle','off');
y1 = gaussmf(x, [0.5 4]);
y2 = gaussmf(x, [2 7]);
yy = probor([y1; y2]);
plot(x,[y1; y2; yy])
psigmf
Purpose
Syntax
y = psigmf(x,[a1 c1 a2 c2])
Description
The sigmoid curve plotted for the vector x depends on two parameters
a and c as given by
f ( x; a, c) =
1
1+ e
a( x c)
psigmf is simply the product of two such curves plotted for the values
of the vector x
Examples
x=0:0.1:10;
y=psigmf(x,[2 3 -5 8]);
plot(x,y)
xlabel('psigmf, P=[2 3 -5 8]')
1
0.75
0.5
0.25
0
0
See Also
4
6
psigmf, P = [2 3 5 8]
10
4-63
readfis
Purpose
Syntax
fismat = readfis('filename')
Description
Read a fuzzy inference system from a .fis file (named filename) and
import the resulting file into the workspace.
fismat = readfis (no input arguments) opens a uigetfile dialog box
Examples
fismat = readfis('tipper');
getfis(fismat)
returns
Name = tipper
Type = mamdani
NumInputs = 2
InLabels =
service
food
NumOutputs = 1
OutLabels =
tip
NumRules = 3
AndMethod = min
OrMethod = max
ImpMethod = min
AggMethod = max
DefuzzMethod = centroid
ans =
tipper
See Also
4-64
writefis
rmmf
Purpose
Syntax
fis = rmmf(fis,'varType',varIndex,'mf',mfIndex)
Description
Examples
a = newfis('mysys');
a = addvar(a,'input','temperature',[0 100]);
a = addmf(a,'input',1,'cold','trimf',[0 30 60]);
getfis(a,'input',1)
returns
Name = temperature
NumMFs = 1
MFLabels =
cold
Range = [0 100]
b = rmmf(a,'input',1,'mf',1);
getfis(b,'input',1)
returns
Name = temperature
4-65
rmmf
NumMFs = 0
MFLabels =
Range = [0 100]
See Also
4-66
rmvar
Purpose
Syntax
fis2 = rmvar(fis,'varType',varIndex)
[fis2,errorStr] = rmvar(fis,'varType',varIndex)
Description
Examples
a = newfis('mysys');
a = addvar(a,'input','temperature',[0 100]);
getfis(a)
returns
Name = mysys
Type
= mamdani
NumInputs = 1
InLabels =
temperature
NumOutputs = 0
OutLabels =
NumRules = 0
AndMethod = min
4-67
rmvar
OrMethod = max
ImpMethod = min
AggMethod = max
DefuzzMethod = centroid
ans =
mysys
b = rmvar(a,'input',1);
getfis(b)
returns
Name = mysys
Type = mamdani
NumInputs = 0
InLabels =
NumOutputs = 0
OutLabels =
NumRules = 0
AndMethod = min
OrMethod = max
ImpMethod = min
AggMethod = max
DefuzzMethod = centroid
ans =
mysys
See Also
4-68
ruleedit
Purpose
Syntax
ruleedit('a')
ruleedit(a)
Description
Menu
Items
On the Rule Editor, there is a menu bar that allows you to open related
GUI tools, open and save systems, and so on. The File menu for the
Rule Editor is the same as the one found on the FIS Editor. Refer to
fuzzy for more information:
Use the following Edit menu item:
Undo to undo the most recent change.
FIS properties to invoke the FIS Editor.
Membership functions to invoke the Membership Function Editor.
Use the following View menu items:
Rules to invoke the Rule Viewer.
Surface to invoke the Surface Viewer.
Use the Options menu items:
Language to select the language: English, Deutsch, and Francais
Format to select the format:
4-69
ruleedit
Verbose uses the words "if," "then," "AND," "OR," and so on to create
actual sentences.
Symbolic substitutes some symbols for the words used in the verbose
mode. For example, if A AND B then C becomes A & B => C.
Indexed mirrors how the rule is stored in the FIS structure.
See Also
4-70
ruleview
Purpose
Syntax
ruleview('a')
Description
Menu
Items
On the Rule Viewer, there is a menu bar that allows you to open related
GUI tools, open and save systems, and so on. The File menu for the
Rule Viewer is the same as the one found on the FIS Editor. Refer to
fuzzy for more information.
Use the Edit menu items:
Undo to undo the most recent action
FIS properties to invoke the FIS Editor
4-71
ruleview
See Also
4-72
setfis
Purpose
Syntax
a = setfis(a,'fispropname','newfisprop')
a = setfis(a,'vartype',varindex,'varpropname','newvarprop')
a = setfis(a,'vartype',varindex,'mf',mfindex,
...
'mfpropname','newmfprop');
Description
The command setfis can be called with three, five, or seven input
arguments, depending on whether you want to set a property of the
entire FIS structure, for a particular variable belonging to that FIS
structure, or for a particular membership function belonging to one of
those variables. The arguments are:
a a variable name of a FIS from the workspace
vartype a string indicating the variable type: input or output
varindex the index of the input or output variable
'mf' a required string for the fourth argument of a
seven-argument call for setfis, indicating this variable is a
membership function
mfindex the index of the membership function belonging to the
chosen variable
'fispropname' a string indicating the property of the FIS field
you want to set: name, type, andmethod, ormethod, impmethod,
aggmethod, defuzzmethod
'newfisprop' a string describing the name of the FIS property or
method you want to set
'varpropname' a string indicating the name of the variable field
you want to set: name or range
'newvarprop' a string describing the name of the variable you
want to set (for name), or an array describing the range of that
variable (for range)
4-73
setfis
Examples
which results in
out =
eating
See Also
4-74
getfis
sffis
Purpose
Syntax
output = sffis(t,x,u,flag,fismat)
Description
See Also
evalfis, fuzblock
4-75
showfis
Purpose
Syntax
showfis(fismat)
Description
Examples
a = readfis('tipper');
showfis(a)
Returns:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
4-76
Name
Type
Inputs/Outputs
NumInputMFs
NumOutputMFs
NumRules
AndMethod
OrMethod
ImpMethod
AggMethod
DefuzzMethod
InLabels
OutLabels
InRange
OutRange
InMFLabels
OutMFLabels
tipper
mamdani
[2 1]
[3 2]
3
3
min
max
min
max
centroid
service
food
tip
[0 10]
[0 10]
[0 30]
poor
good
excellent
rancid
delicious
cheap
showfis
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
42.
43.
44.
42.
43.
44.
42.
43.
44.
See Also
InMFTypes
OutMFTypes
InMFParams
OutMFParams
Rule Antecedent
Rule Consequent
Rule Weight
Rule Connection
average
generous
gaussmf
gaussmf
gaussmf
trapmf
trapmf
trimf
trimf
trimf
[1.5 0 0 0]
[1.5 5 0 0]
[1.5 10 0 0]
[0 0 1 3]
[7 9 10 10]
[0 5 10 0]
[10 15 20 0]
[20 25 30 0]
[1 1]
[2 0]
[3 2]
1
2
3
1
1
1
2
1
2
getfis
4-77
showrule
Purpose
Syntax
showrule(fis)
showrule(fis,indexList)
showrule(fis,indexList,format)
showrule(fis,indexList,format,Lang)
Description
Examples
a = readfis('tipper');
showrule(a,1)
ans =
1. If (service is poor) or (food is rancid)
then (tip is cheap) (1)
showrule(a,2)
ans =
2. If (service is good) then (tip is average) (1)
showrule(a,[3 1],'symbolic')
ans =
3. (service==excellent) | (food==delicious) =>
(tip=generous) (1)
4-78
showrule
See Also
4-79
sigmf
Purpose
Syntax
y = sigmf(x,[a c])
Description
f ( x, a, c ) =
1
1+ e
a( x c )
Examples
x=0:0.1:10;
y=sigmf(x,[2 4]);
plot(x,y)
xlabel('sigmf, P=[2 4]')
1
0.75
0.5
0.25
0
0
4-80
4
6
sigmf, P = [2 4]
10
sigmf
See Also
4-81
smf
Purpose
Syntax
y = smf(x,[a b])
Description
xa
0,
2
2 x a , a x a + b
b a
2
f ( x; a, b) =
2
a+b
x b
x b
1 - 2 b - a ,
2
1,
xb
Examples
x=0:0.1:10;
y=smf(x,[1 8]);
plot(x,y)
xlabel('smf, P=[1 8]')
1
0.75
0.5
0.25
0
0
See Also
4-82
4
6
smf, P = [1 8]
10
subclust
Purpose
Syntax
[C,S] = subclust(X,radii,xBounds,options)
Description
The function returns the cluster centers in the matrix C. Each row of C
contains the position of a cluster center. The returned S vector contains
the sigma values that specify the range of influence of a cluster center
in each of the data dimensions. All cluster centers share the same set
of sigma values.
The subtractive clustering method assumes each data point is a
potential cluster center and calculates a measure of the likelihood that
each data point would define the cluster center, based on the density of
surrounding data points. The algorithm does the following:
Selects the data point with the highest potential to be the first
cluster center
Removes all data points in the vicinity of the first cluster center (as
determined by radii), in order to determine the next data cluster
and its center location
Iterates on this process until all of the data is within radii of a
cluster center
The subtractive clustering method is an extension of the mountain
clustering method proposed by R. Yager.
The matrix X contains the data to be clustered; each row of X is a
data point. The variable radii is a vector of entries between 0 and 1
that specifies a cluster centers range of influence in each of the data
dimensions, assuming the data falls within a unit hyperbox. Small
radii values generally result in finding a few large clusters. The best
values for radii are usually between 0.2 and 0.5.
For example, if the data dimension is two (X has two columns),
radii=[0.5 0.25] specifies that the range of influence in the first data
4-83
subclust
dimension is half the width of the data space and the range of influence
in the second data dimension is one quarter the width of the data
space. If radii is a scalar, then the scalar value is applied to all data
dimensions, i.e., each cluster center has a spherical neighborhood of
influence with the given radius.
xBounds is a 2-by-N matrix that specifies how to map the data in X
4-84
subclust
Examples
[C,S] = subclust(X,0.5)
References
See Also
genfis2
4-85
surfview
Purpose
Syntax
surfview('a')
Description
4-86
surfview
If you want to create a smoother plot, use the Plot points field to specify
the number of points on which the membership functions are evaluated
in the input or output range. This field defaults to a value of 101.
Click Evaluate to perform the calculation and plot the output surface.
By clicking on the plot axes and dragging the mouse, you can
manipulate the surface so that you can view it from different angles.
If there are more than two inputs to your system, you must supply the
constant values associated with any unspecified inputs in the reference
input section.
Refer to The Surface Viewer on page 2-56 for more information about
how to use surfview.
Menu
Items
On the Surface Viewer, there is a menu bar that allows you to open
related GUI tools, open and save systems, and so on. The Surface
Viewer uses the same File menu as the one on the FIS Editor. Refer to
fuzzy for more information:
Use the Edit menu items:
Undo to undo the most recent action
FIS properties to invoke the FIS Editor
Membership functions to invoke the Membership Function Editor
Rules... to invoke the Rule Editor
Use the View menu item:
Rules to invoke the Rule Viewer
Use the Options menu items:
Plot to choose among eight different kinds of plot styles.
Color Map to choose among several different color schemes.
Always evaluate to automatically evaluate and plot a new surface
every time you make a change that affects the plot, such as changing
4-87
surfview
See Also
4-88
trapmf
Purpose
Syntax
y = trapmf(x,[a b c d])
Description
xa
0,
x a
, a x b
b a
f ( x; a, b, c, d ) = 1,
b x c
d x
, c x d
d c
0,
d x
or, more compactly, by
xa d x
f ( x; a, b, c, d ) = max min
, 1,
, o
dc
b a
The parameters a and d locate the feet of the trapezoid and the
parameters b and c locate the shoulders.
Examples
x=0:0.1:10;
y=trapmf(x,[1 5 7 8]);
plot(x,y)
xlabel('trapmf, P=[1 5 7 8]')
4-89
trapmf
1
0.75
0.5
0.25
0
0
See Also
4-90
4
6
trapmf, P = [1 5 7 8]
10
trimf
Purpose
Syntax
y = trimf(x,params)
y = trimf(x,[a b c])
Description
xa
0,
x a
, a x b
b a
f ( x; a, b, c ) =
c x , b x c
cb
0,
xa c x
f ( x; a, b, c ) = max min
,
, o
b a cb
The parameters a and c locate the feet of the triangle and the
parameter b locates the peak.
Examples
x=0:0.1:10;
y=trimf(x,[3 6 8]);
plot(x,y)
xlabel('trimf, P=[3 6 8]')
4-91
trimf
1
0.75
0.5
0.25
0
0
See Also
4-92
4
6
trimf, P = [3 6 8]
10
writefis
Purpose
Syntax
writefis(fismat)
writefis(fismat,'filename')
writefis(fismat,'filename','dialog')
Description
file.
writefis(fismat) opens a dialog box to assist with the naming and
Examples
See Also
a = newfis('tipper');
a = addvar(a,'input','service',[0 10]);
a = addmf(a,'input',1,'poor','gaussmf',[1.5 0]);
a = addmf(a,'input',1,'good','gaussmf',[1.5 5]);
a = addmf(a,'input',1,'excellent','gaussmf',[1.5 10]);
writefis(a,'my_file')
readfis
4-93
zmf
Purpose
Syntax
y = zmf(x,[a b])
Description
1,
xa
2
1 2 x a , a x a + b
2
b a
f ( x; a, b) =
2
a+b
x b
x b
2 b - a ,
2
0,
xb
Examples
x=0:0.1:10;
y=zmf(x,[3 7]);
plot(x,y)
xlabel('zmf, P=[3 7]')
1
0.75
0.5
0.25
0
0
4-94
4
6
zmf, P = [3 7]
10
zmf
See Also
4-95
zmf
4-96
5
Block Reference
Controllers (p. 5-2)
Block Reference
Controllers
5-2
Logical Operators
Logical Operators
Probabilistic OR
Probabilistic OR function in
Simulink software
5-3
Block Reference
Membership Functions
5-4
Diff. Sigmoidal MF
Gaussian MF
Gaussian2 MF
Generalized Bell MF
Pi-shaped MF
Prod. Sigmoidal MF
S-shaped MF
Sigmoidal MF
Trapezoidal MF
Triangular MF
Z-shaped MF
6
Blocks Alphabetical List
Diff. Sigmoidal MF
Purpose
Description
fk ( x) =
1
1 + exp( ak ( x ck ))
where k=1,2. The parameters a1and a2 control the slopes of the left and
right curves. The parameters c1 and c2 control the points of inflection for
the left and right curves. The parameters a1 and a2 should be positive.
See Also
6-2
dsigmf
Purpose
Description
Dialog
Box
See Also
6-3
Purpose
Description
Dialog
Box
FIS matrix
Specify your fuzzy inference system as a fis file or structure.
Refresh rate (sec)
Specify the refresh rate in seconds.
See Also
6-4
Gaussian MF
Purpose
Description
-0.5( x - c)2
f ( x ) = exp
See Also
gaussmf
6-5
Gaussian2 MF
Purpose
Description
0.5( x - ck )2
fk ( x ) = exp
k2
where k=1,2. The parameters c1 and 1 are the mean and variance
defining the left-most curve. The parameters c2 and 2 are the mean and
variance defining the right-most curve.
See Also
6-6
gauss2mf
Generalized Bell MF
Purpose
Description
f ( x) =
1+
x-c
a
2b
where the parameters a and b vary the width of the curve and the
parameter c locates the center of the curve. The parameter b should
be positive.
See Also
gbellmf
6-7
Pi-shaped MF
6-8
Purpose
Description
See Also
pimf
Probabilistic OR
Purpose
Description
y = 1 - prod (1 - x )
See Also
6-9
Purpose
Description
y = 1 - prod (1 - [ a; b])
The two inputs, a and b, are row vectors.
See Also
6-10
probor, Probabilistic OR
Prod. Sigmoidal MF
Purpose
Description
fk ( x ) =
1
1 + exp ( ak ( x - ck ) )
where k=1,2 The parameters a1 and a2 control the slopes of the left and
right curves. The parameters c1 and c2 control the points of inflection
for the left and right curves. Parameters a1 and a2 should be positive
and negative respectively.
See Also
psigmf
6-11
S-shaped MF
6-12
Purpose
Description
See Also
smf
Sigmoidal MF
Purpose
Description
f ( x) =
1
1 + exp(- a( x - c))
When the sign of a is positive the curve increases from left to right.
Conversely, when the sign of a is negative the curve decreases from left
to right. The parameter c sets the point of inflection of the curve.
See Also
sigmf
6-13
Trapezoidal MF
6-14
Purpose
Description
See Also
trapmf
Triangular MF
Purpose
Description
See Also
trimf
6-15
Z-shaped MF
6-16
Purpose
Description
See Also
trimf, zmf
A
Examples
Use this list to find examples in the documentation.
Examples
Introductory Examples
The Nonfuzzy Approach on page 1-12
The Fuzzy Logic Approach on page 1-16
Simulink Examples
An Example: Water Level Control on page 2-87
A-2
B
Bibliography
Bibliography
B-2
Bibliography
B-3
Bibliography
B-4
Glossary
Glossary
Glossary-1
Glossary
Glossary-2
Glossary
subtractive clustering
A technique for automatically generating fuzzy inference systems by
detecting clusters in input-output training data.
Sugeno-type inference
A type of fuzzy inference in which the consequent of each rule is a linear
combination of the inputs. The output is a weighted linear combination
of the consequents.
T-conorm
A two-input function that describes a superset of fuzzy union (OR)
operators, including maximum, algebraic sum, and any of several
parameterized T-conorms Also known as S-norm.
T-norm
A two-input function that describes a superset of fuzzy intersection
(AND) operators, including minimum, algebraic product, and any of
several parameterized T-norms.
Glossary-3
Glossary
Glossary-4
Index
A
evalmf 4-17
addmf 2-81
addrule 2-81
addvar 2-85
Index
aggregation 2-21
AND 2-15
anfis 2-107
options 2-144
anfisedit 2-76
antecedent 2-19
FIS 2-30
C-code 2-171
Editor 2-32
files 2-85
generating 2-118
Mamdani-type 2-37
matrix 2-82
saving a FIS 2-58
structure 2-109
fuzblock 2-94
fuzzification 2-17
fuzzy 4-24
fuzzy c-means clustering 4-18
fuzzy clustering 2-144
fuzzy inference engine 2-171
fuzzy inference system (FIS) 2-3
fuzzy inference system in Simulink 6-3
fuzzy inference system with Ruleviewer in
Simulink 6-4
fuzzy operators 2-13
fuzzy set 2-4
defuzz 4-12
gauss2mf 2-11
gaussian 2-11
gaussmf 2-11
gbellmf 2-11
genfis 2-131
genfis1 2-120
genfis2 2-120
gensurf 2-78
getfis 2-74
B
backpropagation 2-122
defuzzification 2-17
defuzzify 2-26
degree of membership 2-4
distfcm 2-152
dsigmf 2-11
E
error tolerance 2-122
evalfis 2-82
Index-1
Index
I
if-then rules 2-17
antecedent 2-16
implication 2-17
implication 2-17
See also if-then rules
initfcm 2-152
L
logical operations 2-13
M
mam2sug 4-50
Index-2
O
OR 2-15
P
pimf 2-12
plotfis 2-76
plotmf 2-77
probabilistic OR 2-23
probor 2-25
psigmf 2-11
R
readfis 2-73
rmmf 2-85
rmvar 2-85
S
setfis 2-75
sffis 4-75
showfis 2-75
showrule 4-78
sigmf 2-11
Simulink blocks
fuzzy controller with ruleviewer 2-91
Fuzzy Logic Controller 2-88
Simulink, working with 2-87
singleton 2-21
Index
sltank 2-88
smf 2-12
T
T-conorm 2-16
T-norm 2-15
testing data 2-110
U
UNIX
stand-alone fuzzy inference engine 2-176
W
Windows
stand-alone fuzzy inference engine 2-172
writefis 4-93
Z
zmf 2-12
Index-3