You are on page 1of 235

Computation

Visualization
Programming
Fuzzy Logic Toolbox
For Use with MATLAB

Users Guide
Version 2
How to Contact The MathWorks:
508-647-7000 Phone
508-647-7001 Fax
TheMathWorks, I nc. Mail
24 PrimePark Way
Natick, MA 01760-1500
http://www.mathworks.com Web
ftp.mathworks.com Anonymous FTP server
comp.soft-sys.matlab Newsgroup
support@mathworks.com Technical support
suggest@mathworks.com Product enhancement suggestions
bugs@mathworks.com Bugreports
doc@mathworks.com Documentation error reports
subscribe@mathworks.com Subscribinguser registration
service@mathworks.com Order status, licenserenewals, passcodes
info@mathworks.com Sales, pricing, and general information
Fuzzy Logic Toolbox Users Guide
COPYRI GHT 1995 - 1999 by TheMathWorks, I nc.
Thesoftwaredescribed in this document is furnishedunder a licenseagreement. Thesoftwaremay beused
or copiedonly under theterms of thelicenseagreement. Nopart of this manual may bephotocopiedor repro-
duced in any formwithout prior written consent fromTheMathWorks, I nc.
U.S. GOVERNMENT: I f Licenseeis acquiringthePrograms on behalf of any unit or agency of theU.S.
Government, thefollowingshall apply: (a) For units of theDepartment of Defense: theGovernment shall
haveonly therights specified in thelicenseunder which thecommercial computer softwareor commercial
softwaredocumentation was obtained, as set forth in subparagraph (a) of theRights in Commercial
Computer Softwareor Commercial SoftwareDocumentation Clauseat DFARS 227.7202-3, thereforethe
rights set forth herein shall apply; and (b) For any other unit or agency: NOTI CE: Notwithstandingany
other leaseor licenseagreement that may pertain to, or accompany thedelivery of, thecomputer software
and accompanyingdocumentation, therights of theGovernment regardingits use, reproduction, and disclo-
sureareas set forth in Clause52.227-19 (c)(2) of theFAR.
MATLAB, Simulink, Stateflow, HandleGraphics, andReal-TimeWorkshopareregisteredtrademarks and
Target LanguageCompiler aretrademarks of TheMathWorks, I nc.
Other product or brand names aretrademarks or registered trademarks of their respectiveholders.
Printing History: J anuary 1995 First printing
April 1997 Second printing
J anuary 1998 Third printingRevised for MATLAB 5.2
J anuary 1999 Minor revisions for Release11 (Onlineonly)

PHONE
FAX
u
MAIL
INTERNET
@
Forward
Thepast fewyears havewitnessed a rapid growth in thenumber and variety
of applications of fuzzy logic. Theapplications rangefromconsumer products
such as cameras, camcorders, washingmachines, and microwaveovens to
industrial processcontrol, medical instrumentation, decision-support systems,
and portfolioselection.
Tounderstand thereasons for thegrowinguseof fuzzy logic it is necessary,
first, toclarify what is meant by fuzzy logic.
Fuzzy logic has twodifferent meanings. I n a narrowsense, fuzzy logic is a
logical system, which is an extension of multivalued logic. But in a wider
sensewhich is in predominant usetodayfuzzy logic (FL) is almost
synonymous with thetheory of fuzzy sets, a theory which relates toclasses of
objects with unsharp boundaries in which membership is a matter of degree.
I n this perspective, fuzzy logic in its narrowsenseis a branch of FL. What is
important torecognizeis that, even in its narrowsense, theagenda of fuzzy
logic is very different both in spirit and substancefromtheagendas of
traditional multivalued logical systems.
I n theFuzzy Logic Toolbox, fuzzy logic should beinterpreted as FL, that is,
fuzzy logicin its widesense. Thebasicideas underlyingFL areexplainedvery
clearly and insightfully in theI ntroduction. What might beadded is that the
basic concept underlyingFL is that of a linguistic variable, that is, a variable
whosevalues arewords rather than numbers. I n effect, much of FL may be
viewed as a methodology for computingwith words rather than numbers.
Although words areinherently less precisethan numbers, their useis closer to
human intuition. Furthermore, computingwith words exploits thetolerance
for imprecision and thereby lowers thecost of solution.
Another basic concept in FL, which plays a central rolein most of its
applications, is that of a fuzzy if-then ruleor, simply, fuzzy rule. Although
rule-based systems havea longhistory of usein AI , what is missingin such
systems is a machinery for dealingwith fuzzy consequents and/or fuzzy
antecedents. I n fuzzy logic, this machinery is provided by what is called the
calculus of fuzzy rules. Thecalculus of fuzzy rules serves as a basis for what
might becalled theFuzzy Dependency and Command Language(FDCL).
Although FDCL is not used explicitly in Fuzzy Logic Toolbox, it is effectively
oneof its principal constituents. I n this connection, what is important to
Forward
recognizeis that in most of theapplications of fuzzy logic, afuzzy logicsolution
is in reality a translation of a human solution intoFDCL.
What makes theFuzzy Logic Toolbox sopowerful is thefact that most of
human reasoningand concept formation is linked totheuseof fuzzy rules. By
providinga systematic framework for computingwith fuzzy rules, theFuzzy
Logic Toolbox greatly amplifies thepower of human reasoning. Further
amplification results fromtheuseof MATLAB and graphical user interfaces
areas in which TheMathWorks has unparalleled expertise.
A trend which is growingin visibility relates totheuseof fuzzy logic in
combination with neurocomputingand genetic algorithms. Moregenerally,
fuzzy logic, neurocomputing, and genetic algorithms may beviewed as the
principal constituents of what might becalled soft computing. Unlikethe
traditional, hard computing, soft computingis aimed at an accommodation
with thepervasiveimprecision of thereal world. Theguidingprincipleof soft
computingis: Exploit thetolerancefor imprecision, uncertainty, and partial
truth toachievetractability, robustness, and lowsolution cost. I n coming
years, soft computingis likely toplay an increasingly important rolein the
conceptionanddesignof systemswhoseMI Q(MachineI Q) ismuchhigher than
that of systems designed by conventional methods.
Amongvariouscombinationsof methodologiesinsoft computing, theonewhich
hashighest visibilityat thisjunctureisthat of fuzzylogicandneurocomputing,
leadingtoso-calledneuro-fuzzysystems. Within fuzzylogic, such systems play
a particularly important rolein theinduction of rules fromobservations. An
effectivemethoddevelopedby Dr. Roger J angfor this purposeis calledANFI S
(AdaptiveNeuro-Fuzzy I nferenceSystem). This method is an important
component of theFuzzy Logic Toolbox.
TheFuzzy Logic Toolbox is highly impressivein all respects. I t makes fuzzy
logican effectivetool for theconception and design of intelligent systems. The
Fuzzy LogicToolbox is easy tomaster and convenient touse. And last, but not
least important, it providesareader-friendlyandup-to-dateintroductiontothe
methodology of fuzzy logic and its wide-rangingapplications.
Lotfi A. Zadeh
Berkeley, CA
J anuary 10, 1995
i
Contents
BeforeYou Begin
What I s theFuzzy Logic Toolbox? . . . . . . . . . . . . . . . . . . . . . . . . . 6
HowtoUseThis Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
I nstallation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1
Introduction
What Is Fuzzy Logic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Why UseFuzzy Logic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
When Not toUseFuzzy Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
What Can theFuzzy Logic Toolbox Do? . . . . . . . . . . . . . . . . . . . 1-6
An Introductory Example: Fuzzy vs. Non-Fuzzy . . . . . . . . . 1-8
TheNon-Fuzzy Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
TheFuzzy Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13
SomeObservations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
2
Tutorial
TheBigPicture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Foundations of Fuzzy Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Fuzzy Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Membership Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
ii Contents
I f-Then Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Fuzzy InferenceSystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Dinner for Two, Reprise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
TheFuzzy I nferenceDiagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
BuildingSystems with theFuzzy Logic Toolbox . . . . . . . . . . 45
Dinner for Two, fromtheTop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
GettingStarted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
TheFI S Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
TheMembership Function Editor . . . . . . . . . . . . . . . . . . . . . . . . . 52
TheRuleEditor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
TheRuleViewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
TheSurfaceViewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
I mportingand ExportingfromtheGUI Tools . . . . . . . . . . . . . . . 62
CustomizingYour Fuzzy System . . . . . . . . . . . . . . . . . . . . . . . . . 63
WorkingfromtheCommand Line . . . . . . . . . . . . . . . . . . . . . . . 65
SystemDisplay Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Buildinga SystemfromScratch . . . . . . . . . . . . . . . . . . . . . . . . . . 70
FI S Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
TheFI S Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Workingwith Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
An Example: Water Level Control . . . . . . . . . . . . . . . . . . . . . . . . 78
BuildingYour Own Fuzzy Simulink Models . . . . . . . . . . . . . . . . 83
Sugeno-TypeFuzzy Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
An Example: TwoLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
anfis and theANFIS Editor GUI . . . . . . . . . . . . . . . . . . . . . . . . . 92
A ModelingScenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Model Learningand I nferenceThrough ANFI S . . . . . . . . . . . . . 93
Familiarity Breeds Validation: KnowYour Data . . . . . . . . . . . . . 94
SomeConstraints of anfis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
TheANFI S Editor GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
ANFI S Editor GUI Example1:
iii
CheckingData Helps Model Validation . . . . . . . . . . . . . . . . . . . 98
ANFI S Editor GUI Example2:
CheckingData Doesnt ValidateModel . . . . . . . . . . . . . . . . . . 106
anfis fromtheCommand Line . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Moreon anfis and theANFI S Editor GUI . . . . . . . . . . . . . . . . . 114
Fuzzy Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Fuzzy C-Means Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
SubtractiveClustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Stand-AloneC-CodeFuzzy InferenceEngine . . . . . . . . . . . . 130
Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3
Reference
GUI Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Membership Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
FI S Data StructureManagement . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Advanced Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Simulink Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5
iv Contents
BeforeYou Begin
What I s theFuzzy Logic Toolbox? . . . . . . . . . . . . . 2
HowtoUseThis Guide . . . . . . . . . . . . . . . . . 3
I nstallation . . . . . . . . . . . . . . . . . . . . . . 3
Typographical Conventions . . . . . . . . . . . . . . . 4
Before You Begin
6
This section describes howtousetheFuzzy Logic Toolbox. I t explains howto
usethis guideand points you toadditional books for toolbox installation
information.
What Is the Fuzzy Logic Toolbox?
TheFuzzy Logic Toolbox is a collection of functions built on theMATLAB

numeric computingenvironment. I t provides tools for you tocreateand edit


fuzzyinferencesystemswithin theframework of MATLAB, or if you prefer you
can integrateyour fuzzy systems intosimulations with Simulink

, or you can
even build stand-aloneC programs that call on fuzzy systems you build with
MATLAB. This toolbox relies heavily on graphical user interface(GUI ) tools to
help you accomplish your work, although you can work entirely fromthe
command lineif you prefer.
Thetoolbox provides threecategories of tools:
Command linefunctions
Graphical, interactivetools
Simulink blocks and examples
Thefirst category of tools is madeup of functions that you can call fromthe
command lineor fromyour own applications. Many of thesefunctions are
MATLAB M-files, series of MATLAB statements that implement specialized
fuzzy logic algorithms. You can viewtheMATLAB codefor thesefunctions
usingthestatement
type function_name
You can changetheway any toolbox function works by copyingand renaming
theM-file, thenmodifyingyour copy. Youcanalsoextendthetoolboxbyadding
your own M-files.
Secondly, thetoolbox provides anumber of interactivetools that let you access
many of thefunctions through a GUI . Together, theGUI - based tools provide
an environment for fuzzy inferencesystemdesign, analysis, and
implementation.
Thethird category of tools is a set of blocks for usewith theSimulink
simulation software. Thesearespecifically designed for high speed fuzzy logic
inferencein theSimulink environment.
7
How to Use This Guide
If you arenewto fuzzy logic, begin with Chapter 1, I ntroduction.This
chapter introduces themotivation behind fuzzy logic and leads you smoothly
intothetutorial.
If you arean experienced fuzzy logic user, you may want tostart at the
beginningof Chapter 2, Tutorial,tomakesureyou arecomfortablewith the
fuzzy logic terminology in theFuzzy Logic Toolbox. I f you just want an
overviewof each graphical tool and examples of specific fuzzy systemtasks,
turn directly tothesection in Chapter 2 entitled, BuildingSystems with the
Fuzzy Logic Toolbox.This section does not includeinformation on the
adaptivedatamodelingapplication coveredby thetoolbox function anfis. The
basicfunctionalityof this tool can befoundin thesection in Chapter 2entitled,
anfis and theANFI S Editor GUI .
If youjust want tostart assoonaspossibleandexperiment, you can open an
examplesystemright away by typing
fuzzy tipper
ThisbringsuptheFuzzyI nferenceSystem(FI S) editor for anexampledecision
makingproblemthat has todowith howtotip in a restaurant.
All toolbox users shoulduseChapter 3, Reference,for information on specific
tools or functions. Referencedescriptions includea synopsis of thefunctions
syntax, as well as a completeexplanation of options and operation. Many
referencedescriptions alsoincludehelpful examples, a description of the
functions algorithm, and references toadditional readingmaterial. For
GUI -based tools, thedescriptions includeoptions for invokingthetool.
Installation
Toinstall this toolboxon aworkstation or alargemachine, seetheI nstallation
Guidefor UNI X. Toinstall thetoolbox on a PC or Macintosh, seethe
I nstallation Guidefor PC and Macintosh.
Todetermineif theFuzzy Logic Toolbox is already installed on your system,
check for a subdirectory named fuzzy within themain toolbox directory or
folder.
Before You Begin
8
Typographical Conventions
To Indicate This Guide Uses Example
Examplecode Monospace type
(Use Codetag.)
Toassign thevalue5 toA,
enter
A = 5
Function
names
Monospace type
(Use Codetag.)
Thecos function finds the
cosineof each array
element.
Function
syntax
Monospace type for text
that must appear as
shown. (UseCodetag.)
Monospace italics for
components you can
replacewith any variable.
(UseCode-ital tag.)
Themagic function uses
thesyntax
M =magic(n)
Keys Boldfacewith an initial
capital letter
(UseMenu-Bodytext tag.)
Press theReturn key.
Mathematical
expressions
Variables in italics.
Functions, operators, and
constants in standard
type. (Use
EquationVariables tag.)
This vector represents the
polynomial
p =x
2
+2x +3
MATLAB
output
Monospace type
(Use Code tag.)
MATLAB responds with
A =
5
9
Menu names,
menu items,
and controls
Boldfacewith an initial
capital letter
(UseMenu-Bodytext tag.)
ChoosetheFile menu.
Newterms NCS italics
(UseBody text-ital tag.)
An array is an ordered
collection of information.
To Indicate This Guide Uses Example
Before You Begin
10
1
I ntroduction
What Is Fuzzy Logic? . . . . . . . . . . . . . . . . 1-2
Why UseFuzzy Logic? . . . . . . . . . . . . . . . . 1-5
When Not toUseFuzzy Logic . . . . . . . . . . . . . 1-6
What Can theFuzzy Logic Toolbox Do? . . . . . . . . . 1-6
An Introductory Example: Fuzzy vs. Non-Fuzzy . . . . 1-8
TheNon-Fuzzy Approach . . . . . . . . . . . . . . . 1-9
TheFuzzy Approach . . . . . . . . . . . . . . . . . 1-13
SomeObservations . . . . . . . . . . . . . . . . . . 1-14
1 Introduction
1-2
What Is Fuzzy Logic?
Fuzzy logicis all about therelativeimportanceof precision: Howimportant is
it tobeexactly right when a rough answer will do? All books on fuzzy logic
begin with a fewgood quotes on this very topic, and this is noexception. Here
is what someclever peoplehavesaid in thepast:
Precision is not truth.
Henri Matisse
Sometimes themoremeasurabledrives out themost important.
RenDubos
Vagueness is nomoretobedoneawaywith in theworld of logicthan friction in
mechanics.
Charles Sanders Peirce
I believethat nothingis unconditionally true, and henceI amopposed toevery
statement of positivetruth and every man whomakes it.
H. L. Mencken
Sofar as thelaws of mathematics refer toreality, they arenot certain. And so
far as they arecertain, they donot refer toreality.
Albert Einstein
Ascomplexityrises, precisestatementslosemeaningandmeaningful statements
loseprecision.
Lotfi Zadeh
Somepearls of folk wisdomalsoechothesethoughts:
Dont losesight of theforest for thetrees.
Dont bepenny wiseand pound foolish.
TheFuzzy Logic Toolbox for usewith MATLAB is a tool for solvingproblems
with fuzzy logic. Fuzzy logicis a fascinatingarea of research becauseit does a
good job of tradingoff between significanceand precisionsomethingthat
humans havebeen managingfor a very longtime.
Fuzzy logicsometimes appears exoticor intimidatingtothoseunfamiliar with
it, but onceyou becomeacquainted with it, it seems almost surprisingthat no
oneattempted it sooner. I n this sensefuzzy logicis both old and newbecause,
What Is Fuzzy Logic?
1-3
although themodern and methodical scienceof fuzzy logic is still young, the
concepts of fuzzy logic reach right down toour bones.
Fuzzy logicis aconvenient way tomapan input spacetoan output space. This
is thestartingpoint for everythingelse, and thegreat emphasis hereis on the
word convenient.
What doI mean by mappinginput spacetooutput space? Herearea few
examples: You tell mehowgood your servicewas at a restaurant, and I ll tell
you what thetip should be. You tell mehowhot you want thewater, and I ll
adjust thefaucet valvetotheright setting. You tell mehowfar away the
subject of your photograph is, and I ll focus thelens for you. You tell mehow
fast thecar is goingandhowhardthemotor is working, andI ll shift thegears
for you.
A 1500 kg mass
is approaching
your head at
45.3 m/sec.
LOOK
OUT!!
Precision Significance
Precision and Significance in the Real World
1 Introduction
1-4
A graphical exampleof an input-output map is shown below.
I tsall just amatter of mappinginputstotheappropriateoutputs. Betweenthe
input andtheoutput well put ablack boxthat does thework. What couldgoin
theblack box? Any number of things: fuzzy systems, linear systems, expert
systems, neural networks, differential equations, interpolated
multi-dimensional lookuptables, or evenaspiritual advisor, just tonameafew
of thepossibleoptions. Clearly thelist could goon and on.
Of thedozens of ways tomaketheblack box work, it turns out that fuzzy is
often thevery best way. Why shouldthat be?As Lotfi Zadeh, whois considered
tobethefather of fuzzy logic, onceremarked: I n almost every caseyou can
build thesameproduct without fuzzy logic, but fuzzy is faster and cheaper.
Input Space
(all possible service
quality ratings)
Output Space
(all possible tips)
the right tip
for tonight
tonight's service
quality
An input-output map for the tipping problem:
Given the quality of service, how much should I tip?
Black
Box
What Is Fuzzy Logic?
1-5
Why Use Fuzzy Logic?
Hereis a list of general observations about fuzzy logic.
Fuzzy logic is conceptually easy tounderstand.
Themathematical concepts behind fuzzy reasoningarevery simple. What
makesfuzzyniceisthenaturalnessof its approach andnot itsfar-reaching
complexity.
Fuzzy logic is flexible.
With any given system, its easy tomassageit or layer morefunctionality on
top of it without startingagain fromscratch.
Fuzzy logic is tolerant of imprecisedata.
Everythingis impreciseif you look closely enough, but morethan that, most
things areimpreciseeven on careful inspection. Fuzzy reasoningbuilds this
understandingintotheprocess rather than tackingit ontotheend.
Fuzzy logic can model nonlinear functions of arbitrary complexity.
You can createa fuzzy systemtomatch any set of input-output data. This
process is madeparticularly easy by adaptivetechniques likeANFI S
(AdaptiveNeuro-FuzzyI nferenceSystems), whichareavailableintheFuzzy
Logic Toolbox.
Fuzzy logic can bebuilt on top of theexperienceof experts.
I n direct contrast toneural networks, which taketrainingdataandgenerate
opaque, impenetrablemodels, fuzzy logic lets you rely on theexperienceof
peoplewhoalready understand your system.
Fuzzy logic can beblended with conventional control techniques.
Fuzzy systems dont necessarily replaceconventional control methods. I n
manycases fuzzysystemsaugment themandsimplifytheir implementation.
Fuzzy logic is based on natural language.
Thebasis for fuzzy logic is thebasis for human communication. This
observation underpins many of theother statements about fuzzy logic.
Thelast statement is perhaps themost important oneand deserves more
discussion. Natural language, that which is usedby ordinary peopleon a daily
basis, hasbeenshapedbythousandsof yearsof humanhistorytobeconvenient
and efficient. Sentences written in ordinary languagerepresent a triumph of
efficient communication. Wearegenerally unawareof this becauseordinary
languageis, of course, somethingweuseevery day. Sincefuzzy logic is built
1 Introduction
1-6
atopthestructures of qualitativedescription usedin everyday language, fuzzy
logic is easy touse.
When Not to Use Fuzzy Logic
Fuzzy logic is not a cure-all. When should you not usefuzzy logic? Thesafest
statement is thefirst onemadein this introduction: fuzzy logicis aconvenient
way tomap an input spacetoan output space. I f you find its not convenient,
trysomethingelse. I f asimpler solution alreadyexists, useit. Fuzzylogicisthe
codification of common senseusecommon sensewhen you implement it and
you will probably maketheright decision. Many controllers, for example, doa
finejob without usingfuzzy logic. However, if you takethetimetobecome
familiar with fuzzy logic, youll seeit can bea very powerful tool for dealing
quickly and efficiently with imprecision and nonlinearity.
What Can the Fuzzy Logic Toolbox Do?
TheFuzzy Logic Toolbox allows you todoseveral things, but themost
important thingit lets you dois createand edit fuzzy inferencesystems. You
can createthesesystems usinggraphical tools or command-linefunctions, or
you can generatethemautomatically usingeither clusteringor adaptive
neuro-fuzzy techniques.
I f you haveaccess toSimulink, you can easily test your fuzzy systemin ablock
diagramsimulation environment.
Thetoolbox alsolets you run your own stand-aloneC programs directly,
without theneed for Simulink. This is madepossibleby a stand-aloneFuzzy
I nferenceEnginethat reads thefuzzy systems savedfroma MATLAB session.
What Is Fuzzy Logic?
1-7
You can customizethestand-aloneenginetobuild fuzzy inferenceintoyour
own code. All provided codeis ANSI compliant.
Becauseof theintegrated natureof MATLABs environment, you can create
your own tools tocustomizetheFuzzyLogicToolboxor harness it with another
toolbox, suchastheControl System, Neural Network, or OptimizationToolbox,
tomention only a fewof thepossibilities.
Fuzzy
Inference
System
Stand-alone
Fuzzy Engine
MATLAB
Fuzzy
Logic
Toolbox
User-written
M-files
Other toolboxes
Simulink
1 Introduction
1-8
An Introductory Example: Fuzzy vs. Non-Fuzzy
A specific examplewould behelpful at this point. Toillustratethevalueof
fuzzy logic, well showtwodifferent approaches tothesameproblem: linear
and fuzzy. First wewill work through this problemtheconventional
(non-fuzzy) way, writingMATLAB commands that spell out linear and
piecewise-linear relations. Then well takea quick look at thesamesystem
usingfuzzy logic.
Consider thetippingproblem: what is theright amount totip your
waitperson? Hereis a clear statement of theproblem.
TheBasic TippingProblem. Given a number between 0 and 10 that
represents thequality of serviceat a restaurant (where10 is excellent), what
should thetip be?
Cultural footnote: This problemis basedon tippingas it is typically practiced
in theUnited States. An averagetip for a meal in theU.S. is 15%, though the
actual amount may vary dependingon thequality of theserviceprovided.
An Introductory Example: Fuzzy vs. Non-Fuzzy
1-9
The Non-Fuzzy Approach
Lets start with thesimplest possiblerelationship. Supposethat thetipalways
equals 15%of thetotal bill.
tip = 0.15
This doesnt really takeintoaccount thequality of theservice, soweneed to
add a newtermtotheequation. Sinceserviceis rated on a scaleof 0 to10, we
might havethetipgolinearly from5%if theserviceis badto25%if theservice
is excellent. Nowour relation looks likethis:
tip=0.20/10*service+0.05
0 2 4 6 8 10
0
0.05
0.1
0.15
0.2
0.25
service
t
i
p
0 2 4 6 8 10
0.05
0.1
0.15
0.2
0.25
service
t
i
p
1 Introduction
1-10
Sofar sogood. Theformula does what wewant it todo, and its pretty
straightforward. However, wemaywant thetiptoreflect thequalityof thefood
as well. This extension of theproblemis defined as follows:
The Extended Tipping Problem. Given twosets of numbers between 0 and 10
(where10isexcellent) that respectivelyrepresent thequalityof theserviceand
thequality of thefood at a restaurant, what should thetip be?
Lets seehowtheformula will beaffected nowthat weveadded another
variable. Supposewetry:
tip = 0.20/20*(service+food)+0.05;
I n this case, theresults look pretty, but when you look at themclosely, they
dont seemquiteright. Supposeyou want theservicetobea moreimportant
0
5
10
0
5
10
0.05
0.1
0.15
0.2
0.25
service
food
t
i
p
An Introductory Example: Fuzzy vs. Non-Fuzzy
1-11
factor than thefood quality. Lets say that theservicewill account for 80%of
theoverall tippinggrade and thefood will makeup theother 20%. Try:
servRatio=0.8;
tip=servRatio*(0.20/10*service+0.05) + ...
(1servRatio)*(0.20/10*food+0.05);
Theresponseis still somehowtoouniformly linear. Supposeyou want moreof
a flat responsein themiddle, i.e., you want togivea 15%tip in general, and
will depart fromthis plateau only if theserviceis exceptionally good or bad.
This, in turn, means that thosenicelinear mappings nolonger apply. Wecan
still salvagethings byusingapiecewiselinear construction. Lets return tothe
one-dimensional problemof just consideringtheservice. You can string
together a simpleconditional statement usingbreakpoints likethis:
if service<3,
tip=(0.10/3)*service+0.05;
elseif service<7,
tip=0.15;
elseif service<=10,
tip=(0.10/3)*(service7)+0.15;
end
0
5
10
0
5
10
0.05
0.1
0.15
0.2
0.25
service
food
t
i
p
1 Introduction
1-12
Theplot looks likethis.
I f weextend this totwodimensions, wherewetakefood intoaccount again,
somethinglikethis results:
servRatio=0.8;
if service<3,
tip=((0.10/3)*service+0.05)*servRatio + ...
(1servRatio)*(0.20/10*food+0.05);
elseif service<7,
tip=(0.15)*servRatio + ...
(1servRatio)*(0.20/10*food+0.05);
else,
tip=((0.10/3)*(service7)+0.15)*servRatio + ...
(1servRatio)*(0.20/10*food+0.05);
end
0 2 4 6 8 10
0.05
0.1
0.15
0.2
0.25
service
t
i
p
0
5
10
0
5
10
0.05
0.1
0.15
0.2
0.25
service
food
t
i
p
An Introductory Example: Fuzzy vs. Non-Fuzzy
1-13
Wow! Theplot looks good, but thefunction is surprisingly complicated. I t was
a littletricky tocodethis correctly, and its definitely not easy tomodify this
codein thefuture. Moreover, its even less apparent howthealgorithmworks
tosomeonewhodidnt witness theoriginal design process.
The Fuzzy Approach
I t wouldbeniceif wecould just capturetheessentials of this problem, leaving
asideall thefactors that could bearbitrary. I f wemakea list of what really
matters in this problem, wemight end up with thefollowingruledescriptions:
1. I f serviceis poor, then tip is cheap
2. I f serviceis good, then tip is average
3. I f serviceis excellent, then tip is generous
Theorder in which therules arepresented hereis arbitrary. I t doesnt matter
which rules comefirst. I f wewanted toincludethefoods effect on thetip, we
might add thefollowingtworules:
4. I f food is rancid, then tip is cheap
5. I f food is delicious, then tip is generous
I nfact, wecancombinethetwodifferent listsof rulesintoonetight list of three
rules likeso:
1. I f serviceis poor or thefood is rancid, then tip is cheap
2. I f serviceis good, then tip is average
3. I f serviceis excellent or food is delicious, then tip is generous
Thesethreerules arethecoreof our solution. And coincidentally, wevejust
defined therules for a fuzzy logic system. Nowif wegivemathematical
meaningtothelinguisticvariables (what is an averagetip, for example?) we
wouldhaveacompletefuzzyinferencesystem. Of course, theresalot left tothe
methodology of fuzzy logic that werenot mentioningright now, things like:
Howaretherules all combined?
HowdoI definemathematically what an averagetip is?
Thesearequestions weprovidedetailed answers toin thenext fewchapters.
Thedetails of themethod dont really changemuch fromproblemtoproblem
themechanics of fuzzy logic arent terribly complex. What matters is what
1 Introduction
1-14
weveshown in this preliminary exposition: fuzzy is adaptable, simple, and
easily applied.
Hereis thepictureassociated with thefuzzy systemthat solves this problem.
Thepictureabovewas generated by thethreerules above. Themechanics of
howfuzzy inferenceworks is explained TheBigPicture on page2-18,
Foundations of Fuzzy Logic on page2-20, and in Fuzzy I nferenceSystems
on page2-36. I n theBuildingSystems with theFuzzy LogicToolboxon page
2-45, theentiretippingproblemis workedthrough usingthegraphical tools in
theFuzzy Logic Toolbox.
Some Observations
Herearesomeobservations about theexamplesofar. Wefound a piecewise
linear relation that solved theproblem. I t worked, but it was somethingof a
nuisancetoderive, and oncewewroteit down as code, it wasnt very easy to
interpret. On theother hand, thefuzzy systemis based on somecommon
sensestatements. Also, wewereabletoadd twomorerules tothebottomof
thelist that influencedtheshapeof theoverall output without needingtoundo
what had already been done. I n other words, thesubsequent modification was
pretty easy.
Moreover, by usingfuzzy logic rules, themaintenanceof thestructureof the
algorithmdecouplesalongfairlycleanlines. Thenotionof an averagetipmight
changefromdaytoday, citytocity, countrytocountry, but theunderlyinglogic
isthesame: if theserviceisgood, thetipshouldbeaverage. Youcanrecalibrate
themethod quickly by simply shiftingthefuzzy set that defines average
without rewritingthefuzzy rules.
0
5
10
0
5
10
0.05
0.1
0.15
0.2
0.25
service
food
t
i
p
An Introductory Example: Fuzzy vs. Non-Fuzzy
1-15
You can dothis sort of thingwith lists of piecewiselinear functions, but there
is a greater likelihood that recalibration will not besoquick and simple.
For example, hereis thepiecewiselinear tippingproblemslightly rewritten to
makeit moregeneric. I t performs thesamefunction as before, only nowthe
constants can beeasily changed.
% Establish constants
lowTip=0.05; averTip=0.15; highTip=0.25;
tipRange=highTiplowTip;
badService=0; okayService=3;
goodService=7; greatService=10;
serviceRange=greatServicebadService;
badFood=0; greatFood=10;
foodRange=greatFoodbadFood;
% If service is poor or food is rancid, tip is cheap
if service<okayService,
tip=(((averTiplowTip)/(okayServicebadService)) ...
*service+lowTip)*servRatio + ...
(1servRatio)*(tipRange/foodRange*food+lowTip);
% If service is good, tip is average
elseif service<goodService,
tip=averTip*servRatio + (1servRatio)* ...
(tipRange/foodRange*food+lowTip);
% If service is excellent or food is delicious, tip is generous
else,
tip=(((highTipaverTip)/ ...
(greatServicegoodService))* ...
(servicegoodService)+averTip)*servRatio + ...
(1servRatio)*(tipRange/foodRange*food+lowTip);
end
Noticethetendencyhere, as with all code, for creepinggeneralitytorender the
algorithmmoreand moreopaque, threateningeventually toobscureit
completely. What weredoinghereisnt (shouldnt be!) that complicated. True,
wecan fight this tendency tobeobscureby addingstill morecomments, or
perhaps by tryingtorewriteit in slightly moreself-evident ways, but the
mediumis not on our side.
1 Introduction
1-16
Thetruly fascinatingthingtonoticeis that if weremoveeverythingexcept for
threecomments, what remain areexactly thefuzzy rules wewrotedown
before:
% 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
I f, as with a fuzzy system, thecomment is identical with thecode, think how
much morelikely your codeis tohavecomments! Fuzzy logiclets thelanguage
thats clearest toyou, high level comments, alsohavemeaningtothemachine,
which is why its a very successful techniquefor bridgingthegap between
peopleand machines.
Or think of it this way: by makingtheequations as simpleas possible(linear)
wemakethings simpler for themachinebut morecomplicated for us. But
really thelimitation is nolonger thecomputerits our mental model of what
thecomputer is doing. Weall knowthat computers havetheability tomake
things hopelessly complex; fuzzy logic is really about reclaimingthemiddle
ground and lettingthemachinework with our preferences rather than the
other way around. I ts about time.
2
Tutorial
TheBigPicture . . . . . . . . . . . . . . . . . . 2-2
Foundations of Fuzzy Logic . . . . . . . . . . . . . 2-4
Fuzzy InferenceSystems . . . . . . . . . . . . . . 2-20
BuildingSystems with theFuzzy Logic Toolbox . . . . 2-29
WorkingfromtheCommand Line . . . . . . . . . . 2-49
Workingwith Simulink . . . . . . . . . . . . . . . 2-62
Sugeno-TypeFuzzy Inference . . . . . . . . . . . . 2-70
anfis and theANFIS Editor GUI . . . . . . . . . . . 2-76
Fuzzy Clustering . . . . . . . . . . . . . . . . . 2-104
Stand-AloneC-CodeFuzzy InferenceEngine . . . . 2-114
Glossary . . . . . . . . . . . . . . . . . . . . . 2-116
References . . . . . . . . . . . . . . . . . . . . 2-118
2 Tutorial
2-18
The Big Picture
Well start withalittlemotivationfor whereweareheadedinthischapter. The
point of fuzzylogicistomapaninput spacetoanoutput space, andtheprimary
mechanismfor doingthis is a list of if-then statements called rules. All rules
areevaluated in parallel, and theorder of therules is unimportant. Therules
themselves areuseful becausethey refer tovariables and theadjectives that
describethosevariables. Beforewecanbuildasystemthat interpretsrules, we
havetodefineall theterms weplan on usingand theadjectives that describe
them. I f wewant totalk about howhot thewater is, weneedtodefinetherange
that thewaters temperaturecan beexpected tovary over as well as what we
mean by theword hot. Theseareall things well bediscussingin thenext
several sectionsof themanual. Thediagrambelowissomethinglikearoadmap
for thefuzzy inferenceprocess. I t shows thegeneral description of a fuzzy
systemon theleft and a specific fuzzy system(thetippingexamplefromthe
I ntroduction) on theright.
Tosummarizetheconcept of fuzzy inferencedepicted in this figure, fuzzy
inferenceis a method that interprets thevalues in theinput vector and, based
on someset of rules, assigns values totheoutput vector.
This chapter is designed toguideyou through thefuzzy logic process step by
step by providingan introduction tothetheory and practiceof fuzzy logic. The
first threesections of this chapter arethemost importantthey movefrom
Input
The General Case... A Specific Example...
Rules
Input
terms
(interpret)
Output
terms
(assign)
Output service
if service is poor then tip is cheap
if service is good then tip is average
if service is excellent then tip is generous
{poor,
good,
excellent}
{cheap,
average,
generous}
service
is interpreted as
tip
is assigned to be
tip
The Big Picture
2-19
general tospecific, first introducingunderlyingideas and then discussing
implementation details specific tothetoolbox. Thesethreeareas are
Foundations of fuzzy logic, which is an introduction tothegeneral
concepts. I f yourealready familiar with fuzzy logic, you may want toskip
this section.
Fuzzy inferencesystems, which explains thespecific methods of fuzzy
inferenceused in theFuzzy LogicToolbox. Sincethefield of fuzzy logicuses
many terms that donot yet havestandard interpretations, you should
consider readingthissection just tobecomefamiliar with thefuzzyinference
process as it is employed here.
Buildingsystems with theFuzzy Logic Toolbox, which goes intodetail
about howyou build and edit a fuzzy systemusingthis toolbox. This
introduces thegraphical user interfacetools availablein theFuzzy Logic
Toolbox and guides you through theconstruction of a completefuzzy
inferencesystemfromstart tofinish. I f you just want toget up tospeed as
quickly as possible, start here.
After this therearesections that touch on avariety of topics, such as Simulink
use, automaticrulegeneration, anddemonstrations. But fromthepoint of view
of gettingtoknowthetoolbox, thesefirst threesections arethemost crucial.
2 Tutorial
2-20
Foundations of Fuzzy Logic
Everythingis vaguetoa degreeyou donot realizetill you havetried tomakeit
precise. Bertrand Russell
Fuzzy Sets
Fuzzy logicstarts with theconcept of a fuzzy set. A fuzzyset is a set without a
crisp, clearly defined boundary. I t can contain elements with only a partial
degreeof membership.
Tounderstand what a fuzzy set is, first consider what is meant by what we
might call a classical set. A classical set is a container that wholly includes or
wholly excludes any given element. For example, theset of days of theweek
unquestionably includes Monday, Thursday, and Saturday. I t just as
unquestionably excludes butter, liberty, and dorsal fins, and soon.
Wecall this set a classical set becauseits been around for such a longtime. I t
wasAristotlewhofirst formulatedtheLawof theExcludedMiddle, which says
X must either bein set A or in set not-A. Another version runs likethis:
Of any subject, onethingmust beeither asserted or denied.
Hereis a restatement of thelawwith annotations: Of any subject (say
Monday), onething(beingaday of theweek) must beeither assertedor denied
(I assert that Monday is a day of theweek).This lawdemands that opposites,
thetwocategories A and not-A, should between themcontain theentire
universe. Everythingfalls intoeither onegroup or theother. Thereis nothing
that is both a day of theweek and not a day of theweek.
Monday
Thursday
Liberty
Shoe
Polish
Dorsal
Fins
Butter
Saturday
Days of the week
Foundations of Fuzzy Logic
2-21
Nowconsider theset of days comprisinga weekend. Thediagrambelowis one
attempt at classifyingtheweekend days.
Most would agreethat Saturday and Sunday belong, but what about Friday?
I t feelslikea part of theweekend, but somehowit seems likeit should be
technically excluded. Soin thediagramaboveFriday tries its best tosit on the
fence. Classical or normal sets wouldnt toleratethis kind of thing. Either
yourein or youreout. Human experiencesuggests somethingdifferent,
though: fencesittingis a part of life.
Of coursewereontrickygroundhere, becausewerestartingtotakeindividual
perceptions and cultural background intoaccount when wedefinewhat
constitutes theweekend. But this is exactly thepoint. Even thedictionary is
imprecise, definingtheweekend as theperiod fromFriday night or Saturday
toMonday morning.Wereenteringtherealmwheresharpedgedyes-nologic
stops beinghelpful. Fuzzy reasoningbecomes valuableexactly when were
talkingabout howpeoplereally perceivetheconcept weekend as opposed to
a simple-minded classification useful for accountingpurposes only. Morethan
anythingelse, thefollowingstatement lays thefoundations for fuzzy logic:
I n fuzzy logic, thetruth of any statement becomes a matter of degree.
Any statement can befuzzy. Thetool that fuzzy reasoninggives is theability
toreplytoayes-noquestionwithanot-quite-yes-or-noanswer. Thisis thekind
of thingthat humans doall thetime(think howrarely you get a straight
answer toa seemingly simplequestion) but its a rather newtrick for
computers.
Howdoes it work? Reasoningin fuzzy logicis just a matter of generalizingthe
familiar yes-no(Boolean) logic. I f wegivetrue thenumerical valueof 1 and
Monday
Thursday
Liberty Shoe
Polish
Dorsal
Fins
Butter
Saturday
Sunday
Days of the weekend
Friday
2 Tutorial
2-22
false thenumerical valueof 0, weresayingthat fuzzy logic alsopermits
in-between values like0.2 and 0.7453. For instance:
Q: I s Saturday a weekend day?
A: 1 (yes, or true)
Q: I s Tuesday a weekend day?
A: 0 (no, or false)
Q: I s Friday a weekend day?
A: 0.8 (for themost part yes, but not completely)
Q: I s Sunday a weekend day?
A: 0.95 (yes, but not quiteas much as Saturday).
Belowon theleft is aplot that shows thetruth values for weekend-nessif we
areforcedtorespondwith an absoluteyes or noresponse. On theright is aplot
that shows thetruth valuefor weekend-ness if weareallowed torespond with
fuzzy in-between values.
Technically, therepresentation on theright is fromthedomain of multivalued
logic (or multivalent logic). I f I ask thequestion I s X a member of set A? the
answer might beyes, no, or any oneof a thousand intermediatevalues in
between. I n other words, X might havepartial membership in A. Multivalued
logic stands in direct contrast tothemorefamiliar concept of two-valued (or
bivalent yes-no) logic. Two-valuedlogichas playedacentral rolein thehistory
of sciencesinceAristotlefirst codified it, but thetimehas comefor it toshare
thestage.
Toreturn toour example, nowconsider a continuous scaletimeplot of
weekend-ness shown below.
Days of the weekend multivalued membership
w
e
e
k
e
n
d
-
n
e
s
s
w
e
e
k
e
n
d
-
n
e
s
s
Friday Saturday Sunday Monday Thursday
1.0
0.0
Days of the weekend two-valued membership
Friday Saturday Sunday Monday Thursday
1.0
0.0
Foundations of Fuzzy Logic
2-23
By makingtheplot continuous, weredefiningthedegreetowhich any given
instant belongs in theweekend rather than an entireday. I n theplot on the
left, noticethat at midnight on Friday, just as thesecondhandsweeps past 12,
theweekend-ness truth valuejumps discontinuously from0 to1. This is one
way todefinetheweekend, and whileit may beuseful toan accountant, it
doesnt really connect with our real-world experienceof weekend-ness.
Theplot on theright shows asmoothly varyingcurvethat accounts for thefact
that all of Friday, and, toa small degree, parts of Thursday, partakeof the
quality of weekend-ness and thus deservepartial membership in thefuzzy set
of weekend moments. Thecurvethat defines theweekend-ness of any instant
in timeis afunction that maps theinput space(timeof theweek) totheoutput
space(weekend-ness). Specifically it is known as a membershipfunction. Well
discuss this in greater detail in thenext section.
As another exampleof fuzzy sets, consider thequestion of seasons. What
season is it right now?I n thenorthern hemisphere, summer officiallybeginsat
theexact moment in theearths orbit when theNorth Poleis pointed most
directly toward thesun. I t occurs exactly oncea year, in lateJ une. Usingthe
astronomical definitions for theseason, weget sharp boundaries as shown on
theleft in thefigureon thenext page. But what weexperienceas theseasons
varies moreor less continuously as shown on theright below(in temperate
northern hemisphereclimates).
Days of the weekend multivalued membership
w
e
e
k
e
n
d
-
n
e
s
s
w
e
e
k
e
n
d
-
n
e
s
s
Friday Saturday Sunday Monday Thursday
1.0
0.0
Days of the weekend two-valued membership
Friday Saturday Sunday Monday Thursday
1.0
0.0
2 Tutorial
2-24
Membership Functions
A membershipfunction(MF) isacurvethat defines howeach point intheinput
spaceis mapped toa membership value(or degreeof membership) between 0
and 1. Theinput spaceis sometimes referred toas theuniverseof discourse, a
fancy namefor a simpleconcept.
Oneof themost commonly usedexamples of afuzzyset is theset of tall people.
I n this casetheuniverseof discourseis all potential heights, say from3feet to
9feet, and theword tallwould correspond toa curvethat defines thedegree
towhich any person is tall. I f theset of tall peopleis given thewell-defined
(crisp) boundary of a classical set, wemight say all peopletaller than six feet
areofficially considered tall. But such a distinction is clearly absurd. I t may
makesensetoconsider theset of all real numbers greater than six because
numbers belongon an abstract plane, but when wewant totalk about real
people, it is unreasonabletocall oneperson short and another onetall when
they differ in height by thewidth of a hair.
But if thekindof distinction shownaboveisunworkable, thenwhat is theright
waytodefinetheset of tall people?Much as with our plot of weekenddays, the
Time of the year
March March
spring summer fall winter
June September December
1.0
0.0
degree
of
member-
ship
degree
of
member-
ship
Time of the year
March March
spring summer fall winter
June September December
1.0
0.0
You must
be taller
than this
line to be
considered
TALL
excellent!
Foundations of Fuzzy Logic
2-25
figurebelowshows a smoothly varyingcurvethat passes fromnot-tall totall.
Theoutput-axis is anumber known as themembershipvaluebetween 0and1.
Thecurveis known as a membership function and is often given the
designation of . This curvedefines thetransition fromnot tall totall. Both
peoplearetall tosomedegree, but oneis significantly less tall than theother.
Subjectiveinterpretations andappropriateunitsarebuilt right intofuzzysets.
I f I say Shes tall, themembership function tall should already takeinto
account whether I mreferringtoa six-year-old or a grown woman. Similarly,
theunits areincluded in thecurve. Certainly it makes nosensetosay I s she
tall in inches or in meters?
Membership Functions in the Fuzzy Logic Toolbox
Theonly condition a membership function must really satisfy is that it must
vary between 0 and 1. Thefunction itself can bean arbitrary curvewhose
height
degree of
membership,
definitely a tall
person ( = 0.95)
1.0
0.0
really not very
tall at all ( = 0.30)
sharp-edged
membership
function for
TALL
height
degree of
membership,
tall ( = 1.0) 1.0
0.0
not tall ( = 0.0)
continuous
membership
function for
TALL
2 Tutorial
2-26
shapewecan defineas a function that suits us fromthepoint of viewof
simplicity, convenience, speed, and efficiency.
A classical set might beexpressed as
A ={x | x >6}
A fuzzy set is an extension of a classical set. I f X is theuniverseof discourse
and its elements aredenoted by x, then a fuzzy set A in X is defined as a set of
ordered pairs:
A ={x,
A
(x) | x X}

A
(x) is called themembership function (or MF) of x in A. Themembership
function maps each element of X toa membership valuebetween 0 and 1.
TheFuzzy Logic Toolbox includes 11 built-in membership function types.
These11 functions are, in turn, built fromseveral basic functions: piecewise
linear functions, theGaussian distribution function, thesigmoid curve, and
quadraticand cubicpolynomial curves. For detailed information on any of the
membership functions mentioned below, turn toChapter 3, Reference. By
convention, all membership functions havetheletters mf at theend of their
names.
Thesimplest membership functions areformed usingstraight lines. Of these,
thesimplest is thetriangular membership function, and it has thefunction
nametrimf. I ts nothingmorethan a collection of threepoints forminga
triangle. Thetrapezoidal membership function, trapmf, has a flat top and
really is just a truncated trianglecurve. Thesestraight linemembership
functions havetheadvantageof simplicity.
0 2 4 6 8 10
0
0.25
0.5
0.75
1
trimf, P = [3 6 8]
trimf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
trapmf, P = [1 5 7 8]
trapmf
Foundations of Fuzzy Logic
2-27
Twomembership functions arebuilt on theGaussian distribution curve: a
simpleGaussian curveand a two-sided compositeof twodifferent Gaussian
curves. Thetwofunctions aregaussmf and gauss2mf.
Thegeneralized bell membershipfunction is specifiedbythreeparameters and
has thefunction namegbellmf. Thebell membership function has onemore
parameter than theGaussian membership function, soit can approach a
non-fuzzy set if thefreeparameter is tuned. Becauseof their smoothness and
concisenotation, Gaussian and bell membership functions arepopular
methods for specifyingfuzzy sets. Both of thesecurves havetheadvantageof
beingsmooth and nonzeroat all points.
Although theGaussian membership functions and bell membership functions
achievesmoothness, they areunabletospecify asymmetric membership
functions, which areimportant in certain applications. Next wedefinethe
sigmoidal membershipfunction, which is either open left or right. Asymmetric
and closed (i.e. not open totheleft or right) membership functions can be
synthesizedusingtwosigmoidal functions, soinadditiontothebasicsigmf, we
alsohavethedifferencebetween twosigmoidal functions, dsigmf, and the
product of twosigmoidal functions psigmf.
Polynomial based curves account for several of themembership functions in
thetoolbox. ThreerelatedmembershipfunctionsaretheZ, S, andPi curves, all
0 2 4 6 8 10
0
0.25
0.5
0.75
1
gaussmf, P = [2 5]
gaussmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
gauss2mf, P = [1 3 3 4]
gauss2mf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
gbellmf, P = [2 4 6]
gbellmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
dsigmf, P = [5 2 5 7]
dsigmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
psigmf, P = [2 3 5 8]
psigmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
sigmf, P = [2 4]
sigmf
2 Tutorial
2-28
named becauseof their shape. Thefunction zmf is theasymmetrical
polynomial curveopen totheleft, smf is themirror-imagefunction that opens
totheright, and pimf is zeroon both extremes with a risein themiddle.
Theresaverywideselection tochoosefromwhenyoureselectingyour favorite
membership function. And theFuzzy Logic Toolbox alsoallows you tocreate
your ownmembershipfunctionsif youfindthislist toorestrictive. Ontheother
hand, if this list seems bewildering, just remember that you couldprobably get
alongverywell withjust oneor twotypesof membershipfunctions, for example
thetriangleand trapezoid functions. Theselection is widefor thosewhowant
toexplorethepossibilities, but exotic membership functions areby nomeans
required for perfectly good fuzzy inferencesystems. Finally, remember that
moredetails areavailableon all thesefunctions in thereferencesection, which
makes up thesecond half of this manual.
Summary of Membership Functions
Fuzzy sets describevagueconcepts (fast runner, hot weather, weekend
days).
A fuzzy set admits thepossibility of partial membershipin it. (Friday is sort
of a weekend day, theweather is rather hot).
Thedegreean object belongstoafuzzyset is denotedbyamembershipvalue
between 0 and 1. (Friday is a weekend day tothedegree0.8).
A membership function associated with a given fuzzy set maps an input
valuetoits appropriatemembership value.
Logical Operations
Wenowknowwhats fuzzy about fuzzy logic, but what about thelogic?
Themost important thingtorealizeabout fuzzy logical reasoningis thefact
that it is a superset of standard Boolean logic. I n other words, if wekeep the
0 2 4 6 8 10
0
0.25
0.5
0.75
1
pimf, P = [1 4 5 10]
pimf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
smf, P = [1 8]
zmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
zmf, P = [3 7]
smf
Foundations of Fuzzy Logic
2-29
fuzzy values at their extremes of 1 (completely true), and 0 (completely false),
standard logical operations will hold. As an example, consider thestandard
truth tables below:
Nowrememberingthat in fuzzy logicthetruth of any statement is a matter of
degree, howwill thesetruth tables bealtered? Theinput values can bereal
numbers between 0and 1. What function will preservetheresults of theAND
truth table(for example) and alsoextend toall real numbers between 0and 1?
Oneanswer is themin operation. That is, resolvethestatement A AND B,
whereA and B arelimited totherange(0,1), by usingthefunction min(A,B).
Usingthesamereasoning, wecan replacetheOR operation with themax
function, sothat A OR B becomes equivalent tomax(A,B). Finally, the
operation NOT A becomes equivalent totheoperation . Noticehowthe
truth tableaboveis completely unchanged by this substitution.
Moreover, sincethereis a function behind thetruth tablerather than just the
truth tableitself, wecan nowconsider values other than 1 and 0.
Thenext figureuses a graph toshowthesameinformation. Weveconverted
thetruth tabletoa plot of twofuzzy sets applied together tocreateonefuzzy
AND
0
0
1
1
A B A and B A B A or B A not A
0
1
0
1
0
0
0
1
OR
0
0
1
1
0
1
0
1
0
1
1
1
NOT
0
1
1
0
1 A
AND
0
0
1
1
A B min(A,B) A B max(A,B) A 1 - A
0
1
0
1
0
0
0
1
OR
0
0
1
1
0
1
0
1
0
1
1
1
NOT
0
1
1
0
2 Tutorial
2-30
set. Theupper part of thefiguredisplays plots correspondingtothetwo-valued
truth tables above, whilethelower part of thefiguredisplays howthe
operations work over a continuously varyingrangeof truth values A and B
accordingtothefuzzy operations wevedefined.
Given thesethreefunctions, wecan resolveany construction usingfuzzy sets
and thefuzzy logical operation AND, OR, and NOT.
Additional Fuzzy Operators
Weveonly defined hereoneparticular correspondencebetween two-valued
and multivalued logical operations for AND, OR, and NOT. This
correspondenceis by nomeans unique.
I nmoregeneral terms, weredefiningwhat areknownasthefuzzyintersection
or conjunction (AND), fuzzy union or disjunction (OR), and fuzzy complement
(NOT). Wehavedefined abovewhat well call theclassical operators for these
functions: AND =min, OR =max, and NOT =additivecomplement. Typically
most fuzzy logicapplications makeuseof theseoperations andleaveit at that.
I n general, however, thesefunctions arearbitrary toa surprisingdegree. The
Fuzzy Logic Toolbox uses theclassical operator for thefuzzy complement as
shown above, but alsoenables you tocustomizetheAND and OR operators.
Theintersection of twofuzzy sets A and B is specified in general by a binary
mappingT, which aggregates twomembership functions as follows:

AB
(x) =T(
A
(x),
B
(x))
AND
A and B
Two-valued
logic
Multivalued
logic
A and B
A
B
A
A
B
B
A
B
A or B
A or B
A
A
not A
not A
OR NOT
min(A,B) max(A,B) (1-A)
Foundations of Fuzzy Logic
2-31
For example, thebinary operator T may represent themultiplication of
. Thesefuzzy intersection operators, which areusually
referred toas T-norm(Triangular norm) operators, meet thefollowingbasic
requirements.
A T-normoperator is a binary mappingT( ) satisfying:
boundary: T(0, 0) =0, T(a, 1) =T(1, a) =a
monotonicity: T(a, b) <=T(c, d) if a <=c and b <=d
commutativity: T(a, b) =T(b, a)
associativity: T(a, T(b, c)) =T(T(a, b), c)
Thefirst requirement imposes thecorrect generalization tocrisp sets. The
second requirement implies that a decreasein themembership values in A or
B cannot producean increaseinthemembershipvalueinA intersectionB. The
third requirement indicates that theoperator is indifferent totheorder of the
fuzzysetstobecombined. Finally, thefourth requirement allowsustotakethe
intersection of any number of sets in any order of pairwisegroupings.
Likefuzzy intersection, thefuzzy union operator is specified in general by a
binary mappingS:

AB
(x) =S(
A
(x),
B
(x))
For example, thebinary operator S can represent theaddition of
. Thesefuzzy union operators, which areoften referred toas
T-conorm(or S-norm) operators, must satisfythefollowingbasicrequirements.
A T-conorm(or S-norm) operator is a binary mapping S( ) satisfying:
boundary: S(1, 1) =1, S(a, 0) =S(0, a) =a
monotonicity: S(a, b) <=S(c, d) if a <=c and b <=d
commutativity: S(a, b) =S(b, a)
associativity: S(a, S(b, c)) =S(S(a, b), c)
Several parameterizedT-normsanddual T-conormshavebeenproposedinthe
past, suchasthoseof Yager [Yag80], DuboisandPrade[Dub80], Schweizer and
Sklar [Sch63], and Sugeno[Sug77]. Each of theseprovides a way tovary the
gainon thefunction sothat it can bevery restrictiveor very permissive.

A
x ( ) and
B
x ( )
.
,
.

A
x ( ) and
B
x ( )
.
,
.
2 Tutorial
2-32
If-Then Rules
Fuzzy sets and fuzzy operators arethesubjects and verbs of fuzzy logic. These
if-then rulestatements areused toformulatetheconditional statements that
comprisefuzzy logic.
A singlefuzzy if-then ruleassumes theform
if x is A then y is B
whereA and B arelinguistic values defined by fuzzy sets on theranges
(universes of discourse) X and Y, respectively. Theif-part of therulexis Ais
calledtheantecedent or premise, whilethethen-part of theruleyisBiscalled
theconsequent or conclusion. An exampleof such a rulemight be
if serviceis good then tip is average
Notethat good is represented as a number between 0 and 1, and sothe
antecedent is an interpretation that returns a singlenumber between 0and1.
On theother hand, averageisrepresentedasafuzzyset, andsotheconsequent
is an assignment that assigns theentirefuzzy set B totheoutput variabley. I n
theif-then rule, theword is gets used in twoentirely different ways
dependingon whether it appears in theantecedent or theconsequent. I n
MATLAB terms, thisisthedistinction betweenarelational test using==and
avariableassignment usingthe=symbol. A lessconfusingwayof writingthe
rulewould be
if service==good then tip =average
I n general, theinput toan if-then ruleis thecurrent valuefor theinput
variable(in thiscase, service) andtheoutput is an entirefuzzyset (in this case,
average). This set will later bedefuzzified, assigningonevaluetotheoutput.
Theconcept of defuzzification is described in thenext section, on page2-41.
I nterpretingan if-then ruleinvolves distinct parts: first evaluatingthe
antecedent (which involves fuzzifyingtheinput and applyingany necessary
fuzzy operators) and second applyingthat result totheconsequent (known as
implication). I n thecaseof two-valued or binary logic, if-then rules dont
present muchdifficulty. I f thepremiseistrue, thentheconclusionis true. I f we
relax therestrictions of two-valued logic and let theantecedent bea fuzzy
statement, howdoes this reflect on theconclusion?Theanswer is asimpleone:
Foundations of Fuzzy Logic
2-33
if theantecedent is truetosomedegreeof membership, then theconsequent is
alsotruetothat samedegree. I n other words
in binary logic: p q (p and q areeither both trueor both false)
in fuzzy logic: 0.5 p 0.5 q(partial antecedents providepartial implication)
Theantecedent of a rulecan havemultipleparts:
if sky is gray and wind is strongand barometer is falling, then ...
in which caseall parts of theantecedent arecalculated simultaneously and
resolved toa singlenumber usingthelogical operators described in the
precedingsection. Theconsequent of a rulecan alsohavemultipleparts:
if temperatureiscold then hot water valveisopen and cold water valveisshut
in which caseall consequents areaffected equally by theresult of the
antecedent. Howis theconsequent affectedbytheantecedent?Theconsequent
specifies a fuzzy set beassigned totheoutput. Theimplication function then
modifies that fuzzy set tothedegreespecified by theantecedent. Themost
common ways tomodify theoutput fuzzy set aretruncation usingthemin
function (wherethefuzzy set is chopped offas shown below) or scalingusing
theprod function (wheretheoutput fuzzy set is squashed). Both are
supported by theFuzzy LogicToolbox, but weusetruncation for theexamples
in this section.
2 Tutorial
2-34
Summary of If-Then Rules
I nterpretingif-then rules is a three-part process. This process is explained in
detail in thenext section.
delicious
excellent
generous
If service is excellent food is delicious then or tip =generous
food (crisp)
tip (fuzzy)
service (crisp)
3. Apply
implication
operator (min)
2. Apply
OR operator
(max)
1. Fuzzify
inputs

(food==delicious)
=0 .7
(service==excellent)
=0 .0
min(0.7, generous)
Antecedent Consequent
0.0
0.7
0.7
If ( 0.0 0.7 ) then or tip =generous
max(0.0, 0.7) =0.7
If ( 0.7 ) then tip =generous
0.0
0.7 0.7
Foundations of Fuzzy Logic
2-35
1 Fuzzifyinputs: Resolveall fuzzy statements in theantecedent toadegreeof
membershipbetween0and1. I f thereisonlyonepart totheantecedent, this
is thedegreeof support for therule.
2 Applyfuzzyoperator tomultiplepart antecedents: I f therearemultipleparts
totheantecedent, apply fuzzy logicoperators and resolvetheantecedent to
a singlenumber between 0 and 1. This is thedegreeof support for therule.
3 Apply implication method: Usethedegreeof support for theentireruleto
shapetheoutput fuzzy set. Theconsequent of a fuzzy ruleassigns an entire
fuzzy set totheoutput. This fuzzy set is represented by a membership
function that is chosen toindicatethequalities of theconsequent. I f the
antecedent is only partially true, (i.e., is assigned a valueless than 1), then
theoutput fuzzy set is truncated accordingtotheimplication method.
I n general, oneruleby itself doesnt domuch good. Whats needed aretwoor
morerules that can play off oneanother. Theoutput of each ruleis afuzzy set.
Theoutput fuzzy sets for each rulearethen aggregated intoa singleoutput
fuzzy set. Finally theresultingset is defuzzified, or resolved toa single
number. Thenext section shows howthewholeprocess works frombeginning
toend for a particular typeof fuzzy inferencesystemcalled a Mamdani type.
2 Tutorial
2-36
Fuzzy Inference Systems
Fuzzy inferenceis theprocess of formulatingthemappingfroma given input
toan output usingfuzzy logic. Themappingthen provides a basis fromwhich
decisions can bemade, or patterns discerned. Theprocess of fuzzy inference
involves all of thepieces that aredescribed in theprevious sections:
membership functions, fuzzy logic operators, and if-then rules. Therearetwo
types of fuzzy inferencesystems that can beimplemented in theFuzzy Logic
Toolbox: Mamdani-typeandSugeno-type. Thesetwotypesof inferencesystems
vary somewhat in theway outputs aredetermined. Descriptions of thesetwo
types of fuzzy inferencesystems can befound in thereferences, [J an97,
Mam75, Sug85].
Fuzzy inferencesystems havebeen successfully applied in fields such as
automatic control, data classification, decision analysis, expert systems, and
computer vision. Becauseof its multidisciplinary nature, fuzzy inference
systems areassociated with a number of names, such as fuzzy-rule-based
systems, fuzzy expert systems, fuzzy modeling, fuzzy associativememory,
fuzzy logiccontrollers, andsimply (and ambiguously) fuzzy systems. Sincethe
terms used todescribethevarious parts of thefuzzy inferenceprocess arefar
fromstandard, wewill try tobeas clear as possibleabout thedifferent terms
introduced in this section.
Mamdanis fuzzy inferencemethod is themost commonly seen fuzzy
methodology. Mamdanis method was amongthefirst control systems built
usingfuzzyset theory. I t wasproposedin 1975byEbrahimMamdani [Mam75]
asanattempt tocontrol asteamengineandboiler combinationbysynthesizing
a set of linguistic control rules obtained fromexperienced human operators.
Mamdanis effort was based on Lotfi Zadehs 1973 paper on fuzzy algorithms
for complex systems and decision processes [Zad73]. Although theinference
processwedescribeinthenext fewsectionsdifferssomewhat fromthemethods
described in theoriginal paper, thebasic idea is much thesame.
Mamdani-typeinference, as wehavedefined it for theFuzzy Logic Toolbox,
expects theoutput membership functions tobefuzzy sets. After the
aggregation process, thereis a fuzzy set for each output variablethat needs
defuzzification. I ts possible, and in many cases much moreefficient, tousea
singlespikeastheoutput membershipfunctionrather thanadistributedfuzzy
set. This is sometimes known as a singleton output membership function, and
it can bethought of as a pre-defuzzified fuzzy set. I t enhances theefficiency of
thedefuzzification process becauseit greatly simplifies thecomputation
Fuzzy Inference Systems
2-37
required by themoregeneral Mamdani method, which finds thecentroid of a
two-dimensional function. Rather thanintegratingacrossthetwo-dimensional
function tofindthecentroid, weusetheweightedaverageof afewdatapoints.
Sugeno-typesystems support this typeof model. I n general, Sugeno-type
systems can beused tomodel any inferencesystemin which theoutput
membership functions areeither linear or constant.
Dinner for Two, Reprise
I n this section weprovidethesametwo-input one-output three-ruletipping
problemthat you sawin theintroduction, only in moredetail. Thebasic
structureof this exampleis shown in thediagrambelow.
I nformation flows fromleft toright, fromtwoinputs toa singleoutput. The
parallel natureof therules is oneof themoreimportant aspects of fuzzy logic
systems. I nstead of sharp switchingbetween modes based on breakpoints, we
will glidesmoothly fromregions wherethesystems behavior is dominated by
either oneruleor another.
I n theFuzzy LogicToolbox, therearefiveparts of thefuzzy inferenceprocess:
fuzzification of theinput variables, application of thefuzzy operator (AND or
OR) in theantecedent, implication fromtheantecedent totheconsequent,
aggregation of theconsequents across therules, and defuzzification. These
sometimes crypticand odd names havevery specificmeaningthat well define
carefully as westep through each of themin moredetail below.
Input 1
Service (0-10)
Output
Tip (5-25%)
Input 2
Food (0-10)

Dinner for two


a 2 input, 1 output, 3 rule system
All rules are
evaluated in parallel
using fuzzy
reasoning.
The results of the rules
are combined and
distilled (defuzzified).
The result is a crisp
(non-fuzzy) number.
The inputs are crisp
(non-fuzzy) numbers
limited to a specific
range.
If service is excellent or food is delicious,
then tip is generous.
Rule 3
If service is good, then tip is average. Rule 2
If service is poor or food is rancid,
then tip is cheap.
Rule 1
2 Tutorial
2-38
Step 1. Fuzzify Inputs
Thefirst step is totaketheinputs and determinethedegreetowhich they
belongtoeach of theappropriatefuzzy sets via membership functions. I n the
Fuzzy LogicToolbox, theinput is always acrispnumerical valuelimitedtothe
universeof discourseof theinput variable(in this casetheinterval between 0
and 10) and theoutput is a fuzzy degreeof membership in thequalifying
linguisticset (always theinterval between 0 and 1). Fuzzification of theinput
amounts toeither a tablelookup or a function evaluation.
Theexamplewereusingin this section is built on threerules, and each of the
rulesdependsonresolvingtheinputsintoanumber of different fuzzylinguistic
sets: serviceis poor, serviceis good, food is rancid, food is delicious, and soon.
Beforetherules can beevaluated, theinputs must befuzzified accordingto
each of theselinguistic sets. For example, towhat extent is thefood really
delicious? Thefigurebelowshows howwell thefood at our hypothetical
restaurant (ratedon ascaleof 0to10) qualifies, (viaits membershipfunction),
as thelinguistic variabledelicious.I n this case, werated thefood as an 8,
which, given our graphical definition of delicious, corresponds to =0.7for the
delicious membership function.
(Thecompliment tothechef wouldbeyour foodis delicious tothedegree0.7.)
I n this manner, each input is fuzzified over all thequalifyingmembership
functions required by therules.
Step 2. Apply Fuzzy Operator
Oncetheinputs havebeen fuzzified, weknowthedegreetowhich each part of
theantecedent hasbeensatisfiedfor each rule. I f theantecedent of agivenrule
hasmorethanonepart, thefuzzyoperator isappliedtoobtainonenumber that
represents theresult of theantecedent for that rule. This number will then be
applied totheoutput function. Theinput tothefuzzy operator is twoor more
delicious
0.7
food is delicious
food = 8
input
Result of
fuzzification
1. Fuzzify
inputs.
Fuzzy Inference Systems
2-39
membershipvalues fromfuzzifiedinput variables. Theoutput is asingletruth
value.
As is described in thesection on fuzzy logical operations, any number of
well-definedmethods can fill in for theAND operation or theOR operation. I n
theFuzzy Logic Toolbox, twobuilt-in AND methods aresupported: min
(minimum) and prod (product). Twobuilt-in OR methods arealsosupported:
max(maximum), andtheprobabilisticOR methodprobor. TheprobabilisticOR
method (alsoknown as thealgebraic sum) is calculated accordingtothe
equation
probor(a,b) =a +b - ab
I n addition tothesebuilt-in methods, you can createyour own methods for
AND and OR by writingany function and settingthat tobeyour method of
choice. Therewill bemoreinformation on howtodothis later.
Shown belowis an exampleof theOR operator maxat work. Wereevaluating
theantecedent of therule3for thetippingcalculation. Thetwodifferent pieces
of theantecedent (serviceis excellent and food is delicious) yielded thefuzzy
membership values 0.0 and 0.7 respectively. Thefuzzy OR operator simply
selects themaximumof thetwovalues, 0.7, and thefuzzy operation for rule3
iscomplete. I f wewereusingtheprobabilisticOR method, theresult wouldstill
be0.7 in this case.
Step 3. Apply Implication Method
Beforeapplyingtheimplicationmethod, wemust takecareof therulesweight.
Every rulehas a weight (a number between 0 and 1), which is applied tothe
number given by theantecedent. Generally this weight is 1 (as it is for this
example) and soit has noeffect at all on theimplication process. Fromtimeto
delicious
excellent
0.0 0.0
0.7
0.7
service is excellent food is delicious or
food = 8
input 2
result of
fuzzy operator
service = 3
input 1
2. Apply
OR operator (max).
1. Fuzzify
inputs.
2 Tutorial
2-40
timeyou may want toweight onerulerelativetotheothers by changingits
weight valuetosomethingother than 1.
Onceproper weightinghas been assignedtoeach rule, theimplication method
is implemented. A consequent is a fuzzy set represented by a membership
function, which weights appropriately thelinguistic characteristics that are
attributed toit. Theconsequent is reshaped usinga function associated with
theantecedent (a singlenumber). Theinput for theimplication process is a
singlenumber given by theantecedent, and theoutput is a fuzzy set.
I mplication is implementedfor each rule. Twobuilt-in methods aresupported,
and they arethesamefunctions that areused by theAND method: min
(minimum), which truncates theoutput fuzzy set, and prod (product), which
scales theoutput fuzzy set.
Step 4. Aggregate All Outputs
Sincedecisions arebased on thetestingof all of therules in an FI S, therules
must becombined in somemanner in order tomakea decision. Aggregation is
theprocess by which thefuzzy sets that represent theoutputs of each ruleare
combined intoa singlefuzzy set. Aggregation only occurs oncefor each output
variable, just prior tothefifth and final step, defuzzification. Theinput of the
aggregation process is thelist of truncated output functions returned by the
implication process for each rule. Theoutput of theaggregation process is one
fuzzy set for each output variable.
delicious
excellent
generous
If service is excellent food is delicious then or tip =generous
food = 8
input 2
result of
implication
service = 3
input 1
3. Apply
Implication
operator (min).
2. Apply
OR operator (max).
1. Fuzzify
inputs.
Antecedent Consequent
Fuzzy Inference Systems
2-41
Noticethat as longas theaggregation methodis commutative(which it always
should be), then theorder in which therules areexecuted is unimportant.
Threebuilt-in methods aresupported: max (maximum), probor (probabilistic
or), and sum(simply thesumof each rules output set).
I n thediagrambelow, all threerules havebeen placed together toshowhow
theoutput of eachruleiscombined, or aggregated, intoasinglefuzzyset whose
membership function assigns a weightingfor every output (tip) value.
Step 5. Defuzzify
Theinput for thedefuzzification process is a fuzzy set (theaggregateoutput
fuzzy set) and theoutput is a singlenumber. As much as fuzziness helps the
ruleevaluation duringtheintermediatesteps, thefinal desiredoutput for each
variableis generally a singlenumber. However, theaggregateof a fuzzy set
encompasses a rangeof output values, and somust bedefuzzified in order to
resolvea singleoutput valuefromtheset.
4. Apply
aggregation
method (max).
2. Apply
fuzzy
operation
(OR=max).
1. Fuzzify inputs.
3. Apply
implication
method (min).
0 25% 0 25%
0 25% 0 25%
0 25% 0 25%
0 25%
delicious
average
good
excellent
rancid cheap poor
generous
food = 8
input 2
Result of
aggregation
rule 2 has
no dependency
on input 2
service = 3
input 1
If service is poor food is rancid then or tip =cheap
If service is good then tip =average
If service is excellent food is delicious then or tip =generous
1.
2.
3.
2 Tutorial
2-42
Perhaps themost popular defuzzification method is thecentroid calculation,
which returns thecenter of area under thecurve. Therearefivebuilt-in
methods supported: centroid, bisector, middleof maximum(theaverageof the
maximumvalueof theoutput set), largest of maximum, and smallest of
maximum.
The Fuzzy Inference Diagram
Thefuzzy inferencediagramis thecompositeof all thesmaller diagrams weve
been lookingat sofar in this section. I t simultaneously displays all parts of the
fuzzy inferenceprocess weveexamined. I nformation flows through thefuzzy
inferencediagramas shown below.
Noticehowtheflowproceeds up fromtheinputs in thelower left, then across
each row, or rule, and then down theruleoutputs tofinish in thelower right.
This is a very compact way of showingeverythingat once, fromlinguistic
variablefuzzification all theway through defuzzification of theaggregate
output.
5. Defuzzify the
aggregate output
(centroid).
Result of
defuzzification
tip = 16.7%
0 25%
Interpreting the
Fuzzy Inference
Diagram
input 2 input 1
1. if and then
2. if and then
output
Fuzzy Inference Systems
2-43
Shown belowis thereal full-sizefuzzy inferencediagram. Theres a lot tosee
in a fuzzy inferencediagram, but onceyou becomeaccustomed toit, you can
learn a lot about a systemvery quickly. For instance, fromthis diagramwith
theseparticular inputs, you can easily seethat theimplication method is
truncation with themin function. Themaxfunction is beingusedfor thefuzzy
OR operation. Rule3 (thebottom-most rowin thediagramshown opposite) is
havingthestrongest influenceon theoutput. And soon. TheRuleViewer
described in TheRuleVieweron page2-59is a MATLAB implementation of
thefuzzy inferencediagram.
Customization
Oneof theprimary goals of theFuzzy Logic Toolbox is tohavean open and
easily modified fuzzy inferencesystemstructure. Thus, theFuzzy Logic
Toolbox is designed togiveyou as much freedomas possible, within thebasic
5. Defuzzify
(centroid).
4. Apply
aggregation
method (max).
2. Apply
fuzzy
operation
(OR=max).
1. Fuzzify inputs.
3. Apply
implication
method (min).
0% 25%
0% 25%
0% 25%
0% 25%
0% 25%
delicious
average
good
excellent
rancid cheap poor
food = 8
input 2
output
rule 2 has
no dependency
on input 2
tip = 16.7%
service = 3
input 1
If service is poor food is rancid tip =cheap then or
If service is good then tip =average
If service is excellent food is delicious then or tip =generous
1.
2.
3.
0% 25%
0 10
generous
0 10
0 10
0 10 0 10
0% 25%
2 Tutorial
2-44
constraints of theprocess described here, tocustomizethefuzzy inference
process for your application. For example, you can substituteyour own
MATLAB functions for any of thedefault functions used in thefivesteps
detailed above: you makeyour own membership functions, AND methods, OR
methods, implication methods, aggregation methods, and defuzzification
methods. Thenext section describes exactly howtobuild and implement a
fuzzy inferencesystemusingthetools provided.
Building Systems with the Fuzzy Logic Toolbox
2-45
Building Systems with the Fuzzy Logic Toolbox
Dinner for Two, from the Top
Nowweregoingtowork through a similar tippingexample, only well be
buildingit usingthegraphical user interface(GUI ) toolsprovidedbytheFuzzy
LogicToolbox. AlthoughitspossibletousetheFuzzyLogicToolboxbyworking
strictly fromthecommand line, in general its much easier tobuild a system
graphically. Therearefiveprimary GUI tools for building, editing, and
observingfuzzy inferencesystems in theFuzzy Logic Toolbox: theFuzzy
I nferenceSystemor FI S Editor, theMembership Function Editor, theRule
Editor, theRuleViewer, and theSurfaceViewer. TheseGUI s aredynamically
linked, in that changes you maketotheFI S usingoneof them, can affect what
you seeon anyof theother open GUI s. You can haveanyor all of themopen for
any given system.
I n addition tothesefiveprimary GUI s, thetoolbox includes thegraphical
ANFI S Editor GUI , which is used for buildingand analyzingSugeno-type
adaptiveneural fuzzy inferencesystems. TheANFI S Editor GUI is discussed
later in this chapter, in thesection, Sugeno-TypeFuzzy I nferenceon page
2-86.
2 Tutorial
2-46
TheFI S Editor handles thehigh level issues for thesystem: Howmany input
andoutput variables? What aretheir names?TheFuzzy LogicToolbox doesnt
limit thenumber of inputs. However, thenumber of inputs may belimited by
theavailablememory of your machine. I f thenumber of inputs is toolarge, or
thenumber of membership functions is toobig, then it may alsobedifficult to
analyzetheFI S usingtheother GUI tools.
TheMembership Function Editor is used todefinetheshapes of all the
membership functions associated with each variable.
TheRuleEditor is for editingthelist of rules that defines thebehavior of the
system.
Fuzzy
Inference
System
FIS Editor
Membership
Function Editor
Rule Editor
Rule Viewer Surface Viewer
Read-only
tools
Building Systems with the Fuzzy Logic Toolbox
2-47
TheRuleViewer and theSurfaceViewer areused for lookingat, as opposed to
editing, theFI S. They arestrictly read-only tools. TheRuleViewer is a
MATLAB-baseddisplay of thefuzzy inferencediagramshown at theendof the
last section. Used as a diagnostic, it can show(for example) which rules are
active, or howindividual membership function shapes areinfluencingthe
results. TheSurfaceViewer is used todisplay thedependency of oneof the
outputs on any oneor twoof theinputsthat is, it generates and plots an
output surfacemap for thesystem.
This chapter began with an illustration similar totheonebelowdescribingthe
mainparts of afuzzyinferencesystem, onlytheonebelowshowshowthethree
Editors fit together. ThetwoViewers examinethebehavior of theentire
system.
Thefiveprimary GUI s can all interact and exchangeinformation. Any oneof
themcan read and writeboth totheworkspaceand tothedisk (theread-only
viewers can still exchangeplots with theworkspaceand/or thedisk). For any
fuzzy inferencesystem, any or all of thesefiveGUI s may beopen. I f morethan
oneof theseeditors is open for a singlesystem, thevarious GUI windows are
awareof theexistenceof theothers, and will, if necessary, updaterelated
windows. Thus if thenames of themembership functions arechanged using
theMembership Function Editor, thosechanges arereflected in therules
shown in theRuleEditor. Theeditors for any number of different FI S systems
may beopen simultaneously. TheFI S Editor, theMembership Function
Editor, andtheRuleEditor can all readandmodify theFI S data, but theRule
Viewer and theSurfaceViewer donot modify theFI S data in any way.
Input
The General Case... A Specific Example...
Rules
Input
terms
(interpret)
Output
terms
(assign)
Output service
if service is poor then tip is cheap
if service is good then tip is average
if service is excellent then tip is generous
{poor,
good,
excellent}
{cheap,
average,
generous}
service = tip =
tip
The GUI Editors...
The FIS Editor
The Rule Editor
The Membership
Function Editor
2 Tutorial
2-48
Getting Started
Well start with a basicdescription of a two-input, one-output tippingproblem
(based on tippingpractices in theU.S.).
The Basic Tipping Problem. Given a number between 0and 10that represents the
quality of serviceat a restaurant (where10 is excellent), and another number
between 0 and 10 that represents thequality of thefood at that restaurant
(again, 10 is excellent), what should thetip be?
Thestartingpoint is towritedown thethreegolden rules of tipping, based on
years of personal experiencein restaurants.
1. I f theserviceis poor or thefood is rancid, then tip is cheap.
2. I f theserviceis good, then tip is average.
3. I f theserviceis excellent or thefood is delicious, then tip is generous.
Well assumethat an averagetipis 15%, agenerous tipis 25%, andacheaptip
is 5%. I ts alsouseful tohavea vagueidea of what thetippingfunction should
look like.
Obviously thenumbers and theshapeof thecurvearesubject tolocal
traditions, cultural bias, and soon, but thethreerules arepretty universal.
Nowweknowtherules, and wehavean idea of what theoutput should look
like. Lets begin workingwith theGUI tools toconstruct a fuzzy inference
systemfor this decision process.
.25
.15
.5
Bad service or bad food Great service or great food
Building Systems with the Fuzzy Logic Toolbox
2-49
The FIS Editor
Thefollowingdiscussion walks you through buildinga newfuzzy inference
systemfromscratch. I f you want tosavetimeandfollowalongquickly, you can
load thealready built systemby typing
fuzzy tipper
This will loadtheFI S associatedwith thefiletipper.fis (the.fis is implied)
and launch theFI S Editor. However, if you load thepre-built system, you will
not bebuildingrules and constructingmembership functions.
TheFI S Editor displays general information about a fuzzy inferencesystem.
Theres a simplediagramat thetop that shows thenames of each input
variableon theleft, andthoseof each output variableon theright. Thesample
membership functions shown in theboxes arejust icons and donot depict the
actual shapes of themembership functions.
Belowthediagramis thenameof thesystemand thetypeof inferenceused.
Thedefault, Mamdani-typeinference, is what wevebeen describingsofar and
This status line describes the
most recent operation.
These pop-up menus are used to
adjust the fuzzy inference functions,
such as the defuzzification method.
The name of the system is displayed
here. It can be changed using one of the
Save as... menu options.
These menu items allow you to save, open,
or edit a fuzzy system using any of the five
basic GUI tools.
Double-click on an input
variable icon to open the
Membership Function Editor.
Double-click on the system
diagram to open the
Rule Editor.
Double-click on the icon for
the output variable, tip, to
open the Membership
Function Editor.
This edit field is used to name
and edit the names of the
input and output variable.
2 Tutorial
2-50
what well continuetousefor this example. Another slightly different typeof
inference, called Sugeno-typeinference, is alsoavailable. This method is
explained in Sugeno-TypeFuzzy I nference on page2-86. Belowthenameof
thefuzzy inferencesystem, on theleft sideof thefigure, arethepop-upmenus
that allowyou tomodify thevarious pieces of theinferenceprocess. On the
right sideat thebottomof thefigureistheareathat displaysthenameof either
an input or output variable, its associated membership function type, and its
range. Thelatter twofields arespecified only after themembership functions
havebeen. Belowthat region aretheHelp and Closebuttons that call up
onlinehelp and closethewindow, respectively. At thebottomis a status line
that relays information about thesystem.
Tostart this systemfromscratch, type
fuzzy
at theMATLAB prompt. ThegenericuntitledFI S Editor opens, withoneinput,
labeled input1, and oneoutput, labeled output1. For this example, wewill
construct a two-input, oneoutput system, sogototheEdit menu and select
Addinput. A secondyellowbox labeledinput2will appear. Thetwoinputs we
will havein our exampleareserviceandfood. Our oneoutput is tip. Wedlike
tochangethevariablenames toreflect that, though.
1 Click onceon theleft-hand (yellow) box marked input1(thebox will be
highlighted in red).
2 I n thewhiteedit field on theright, changeinput1 to service and press
Return.
3 Click onceon theleft-hand (yellow) box marked input2(thebox will be
highlighted in red).
4 I n thewhiteedit fieldon theright, changeinput2 tofood andpress Return.
5 Click onceon theright-hand (blue) box marked output1.
6 I n thewhiteedit field on theright, changeoutput1 to tip.
Building Systems with the Fuzzy Logic Toolbox
2-51
7 FromtheFilemenu select Saveto workspaceas....
8 Enter thevariablenametipper and click on OK.
You will seethediagramupdated toreflect thenewnames of theinput and
output variables. Thereis nowa newvariablein theworkspacecalled tipper
that containsall theinformationabout thissystem. Bysavingtotheworkspace
with a newname, you alsorenametheentiresystem. Your windowwill look
somethinglikethis.
Leavetheinferenceoptions in thelower left in their default positions for now.
Youveentered all theinformation you need for this particular GUI . Next
definethemembership functions associated with each of thevariables. Todo
2 Tutorial
2-52
this, open theMembership Function Editor. You can open theMembership
Function Editor in oneof threeways:
Pull down theViewmenu itemand select Edit Membership Functions....
Double-click on theicon for theoutput variable, tip.
Typemfedit at thecommand line.
The Membership Function Editor
TheMembershipFunction Editor sharessomefeatures with theFI S Editor. I n
fact, all of thefivebasicGUI tools havesimilar menu options, status lines, and
HelpandClosebuttons. TheMembershipFunction Editor is thetool that lets
This status line describes
the most recent operation.
This edit field lets you set
the display range of the
current plot.
This edit field lets
you set the range of
the current variable.
These menu items allow you
to save, open, or edit a fuzzy
system using any of the five
basic GUI tools.
This is the Variable Palette
area. Click on a variable here
to make it current and edit its
membership functions.
This graph field displays all
the membership functions
of the current variable.
This pop-up menu lets
you change the type
of the current
membership function.
These text fields display
the name and type of
the current variable.
This edit field lets
you change the
numerical
parameters for the
current membership
function.
Click on a line to select it and you
can change any of its attributes,
including name, type and
numerical parameters. Drag your
mouse to move or change the shape
of a selected membership function.
This edit field lets you
change the name of the
current membership
function.
Building Systems with the Fuzzy Logic Toolbox
2-53
you display and edit all of themembership functions associated with all of the
input and output variables for theentirefuzzy inferencesystem.
When you open theMembership Function Editor towork on a fuzzy inference
systemthat does not already exist in theworkspace, therearenot yet any
membershipfunctions associatedwith thevariables that you havejust defined
with theFI S Editor.
On theupper left sideof thegraph area in theMembership Function Editor is
a VariablePalette that lets you set themembership functions for a given
variable.Toset up your membership functions associated with an input or an
output variablefor theFI S, select an FI S variablein this region by clickingon
it.
Next select theEdit pull-down menu, and chooseAdd MFs.... A newwindow
will appear, which allows you toselect both themembershipfunction typeand
thenumber of membership functions associated with theselected variable. I n
thelower right corner of thewindowarethecontrols that let you changethe
name, type, and parameters (shape), of themembership function, onceit has
been selected.
Themembershipfunctions fromthecurrent variablearedisplayedin themain
graph. Thesemembership functions can bemanipulated in twoways. You can
first usethemousetoselect a particular membershipfunction associated with
agiven variablequality, (such as poor, for thevariable, service), andthen drag
themembership function fromsidetoside. This will affect themathematical
description of thequalityassociatedwiththat membershipfunction for agiven
variable. Theselected membership function can alsobetagged for dilation or
contraction by clickingon thesmall squaredragpoints on themembership
function, and then draggingthefunction with themousetoward theoutside,
for dilation, or toward theinside, for contraction. This will changethe
parameters associated with that membership function.
BelowtheVariablePaletteissomeinformation about thetypeandnameof the
current variable. Thereis a text field in this region that lets you changethe
limits of thecurrent variables range(universeof discourse) and another that
lets you set thelimits of thecurrent plot (which has noreal effect on the
system).
Theprocess of specifyingtheinput membership functions for this twoinput
tipper problemis as follows:
2 Tutorial
2-54
1 Select theinput variable, service, by double-clickingon it. Set both the
Rangeand theDisplay Rangetothevector [0 10].
2 Select Add MFs... fromtheEdit menu. Thewindowbelowpops open.
3 Usethepull-down tabtochoosegaussmf for MF Typeand3 for Number of
MFs. This adds threeGaussian curves totheinput variableservice
4 Click onceon thecurvewith theleftmost hump. Changethenameof the
curvetopoor. Toadjust theshapeof themembership function, either use
themouse, as described above, or typein a desired parameter change, and
then click on themembership function. Thedefault parameter listingfor
this curveis [1.5 0].
5 Namethecurvewith themiddlehump, good, and thecurvewith the
rightmost hump, excellent. Reset theassociated parameters if desired.
6 Select theinput variable, food, byclickingon it. Set both theRangeandthe
Display Rangetothevector [0 10].
7 Select Add MFs... fromtheEdit menu and add twotrapmf curves tothe
input variablefood.
8 Click oncedirectly on thecurvewith theleftmost trapazoid. Changethe
nameof thecurvetorancid. Toadjust theshapeof themembership
function, either usethemouse, as described above, or typein a desired
parameter change, and then click on themembership function. Thedefault
parameter listingfor this curveis [0 0 1 3].
9 Namethecurvewith therightmost trapazoid, delicious, and reset the
associated parameters if desired
Building Systems with the Fuzzy Logic Toolbox
2-55
Next you needtocreatethemembershipfunctions for theoutput variable, tip.
Tocreatetheoutput variablemembership functions, usetheVariablePalette
on theleft, selectingtheoutput variable, tip. Theinputs ranged from0 to10,
but theoutput scaleis goingtobea tip between 5 and 25 percent.
Usetriangular membershipfunction types for theoutput. First, set theRange
(and theDisplay Range) to[0 30], tocover theoutput range. I nitially, the
cheap membership function will havetheparameters [0 5 10], theaverage
membership function will be [10 15 20], and thegenerous membership
function will be [20 25 30]. Your systemshould look somethinglikethis.
Nowthat thevariables havebeen named, and themembership functions have
appropriateshapes andnames, yourereadytowritedown therules. Tocall up
theRuleEditor, gototheViewmenu andselect Edit rules..., or typeruleedit
at thecommand line.
2 Tutorial
2-56
The Rule Editor
Constructingrules usingthegraphical RuleEditor interfaceis fairly
self-evident. Based on thedescriptions of theinput and output variables
defined with theFI S Editor, theRuleEditor allows you toconstruct therule
statements automatically, by clickingon and selectingoneitemin each input
variablebox, oneitemin each output box, and oneconnection item. Choosing
noneas oneof thevariablequalities will excludethat variablefroma given
rule. Choosingnot under anyvariablenamewill negatetheassociatedquality.
Rulesmaybechanged, deleted, or added, byclickingontheappropriatebutton.
TheRuleEditor alsohas somefamiliar landmarks, similar tothosein theFI S
Editor and theMembership Function Editor, includingthemenu bar and the
status line. TheFormat pop-upmenu is availablefromtheOptionspull-down
menu fromthetop menu barthis is used toset theformat for thedisplay.
The menu items allow
you to save, open, or
edit a fuzzy system
using any of the five
basic GUI tools.
This status line
describes the most
recent operation.
The rules are
entered
automatically
using the GUI
tools.
Create or edit rules with the GUI buttons and
choices from the input or output selection menus.
Link input
statements in rules.
Negate input or output
statements in rules.
Input or output selection menus.
The Help button
gives some
information about
how the Rule
Editor works, and
the Close button
closes the window.
Building Systems with the Fuzzy Logic Toolbox
2-57
Similarly, Languagecan beset fromunder Optionsas well. TheHelp button
will bringup a MATLAB Help window.
Toinsert thefirst rulein theRuleEditor, select thefollowing:
poor under thevariableservice
rancid under thevariablefood
theradiobutton, or, in theConnection block
cheap, under theoutput variable, tip.
Theresultingruleis:
1. I f (serviceis poor) or (food is rancid) then (tip is cheap) (1)
Thenumbers in theparentheses represent weights that can beappliedtoeach
ruleif desired. You can specify theweights by typingin a desired number
between zeroandoneunder theWeight:setting. I f youdonot specifythem, the
weights areassumed tobeunity (1).
Followa similar proceduretoinsert thesecond and third rules in theRule
Editor toget:
1. I f (serviceis poor) or (food is rancid) then (tip is cheap) (1)
2. I f (serviceis good) then (tip is average) (1)
3. I f (serviceis excellent) or (food is delicious) then (tip is generous) (1)
Tochangea rule, first click on theruletobechanged. Next makethedesired
changes tothat rule, and then click on Changerule. For example, tochange
thefirst ruleto
1. I f (servicenot poor) or (food not rancid) then (tip is not cheap) (1)
click not under each variable, and then click Changerule.
TheFormat pop-upmenufromtheOptionsmenuindicatesthat yourelooking
at theverboseformof therules. Try changingit tosymbolic. You will see
1. (service==poor) =>(tip=cheap) (1)
2. (service==good) =>(tip=average) (1)
3. (service==excellent) =>(tip=generous) (1)
2 Tutorial
2-58
Thereis not much differencein thedisplay really, but its slightly more
languageneutral, sinceit doesnt depend on terms likeifand then.I f you
changetheformat toindexed, youll seeanextremelycompressedversionof the
rules that has squeezed all thelanguageout.
1, 1 (1) : 1
2, 2 (1) : 1
3, 3 (1) : 1
This is theversion that themachinedeals with. Thefirst column in this
structurecorresponds totheinput variable, thesecond column corresponds to
theoutput variable, thethirdcolumn displays theweight appliedtoeach rule,
and thefourth column is shorthand that indicates whether this is an OR (2)
ruleor anAND(1) rule. Thenumbersinthefirst twocolumnsrefer totheindex
number of themembership function. A literal interpretation of rule1 is: if
input 1 is MF1 (thefirst membership function associated with input 1) then
output 1shouldbeMF1(thefirst membershipfunction associatedwith output
1) with theweight 1.Sincethereis only oneinput for this system, theAND
connectiveimplied by the1 in thelast column is of noconsequence.
Thesymbolic format doesnt bother with theterms, if, then, and soon. The
indexed format doesnt even bother with thenames of your variables.
Obviously thefunctionality of your systemdoesnt depend on howwell you
havenamed your variables and membership functions. Thewholepoint of
namingvariables descriptively is, as always, makingthesystemeasier for you
tointerpret. Thus, unless you havesomespecial purposein mind, it will
probably beeasier for you tostick with theverboseformat.
At this point, thefuzzy inferencesystemhas been completely defined, in that
thevariables, membership functions, and therules necessary tocalculatetips
arein place. I t wouldbenice, at this point, tolook at afuzzyinferencediagram
liketheonepresented at theend of theprevious section and verify that
everythingis behavingtheway wethink it should. This is exactly thepurpose
of theRuleViewer, thenext of theGUI toolswell look at. FromtheViewmenu,
select Viewrules....
Building Systems with the Fuzzy Logic Toolbox
2-59
The Rule Viewer
TheRuleViewer displays a roadmap of thewholefuzzy inferenceprocess. I ts
basedonthefuzzyinferencediagramdescribedintheprevioussection. Yousee
a singlefigurewindowwith 10 small plots nested in it. Thethreesmall plots
acrossthetopof thefigurerepresent theantecedent andconsequent of thefirst
rule. Each ruleis a rowof plots, and each column is a variable. Thefirst two
columns of plots (thesix yellowplots) showthemembership functions
referenced by theantecedent, or theif-part of each rule. Thethird column of
plots (thethreeblueplots) shows themembership functions referenced by the
consequent, or thethen-part of each rule. I f you click onceon a rulenumber,
thecorrespondingrulewill bedisplayedat thebottomof thefigure. Noticethat
Each row of plots
represents one rule (here
there are 3). Click on a
rule to display it in the
status bar.
The menu items allow
you to save, open, or edit
a fuzzy system using any
of the five basic GUI
tools.
This edit field allows you
to set the input
explicitly.
This status line describes the most recent operation.
Each column of plots (yellow) shows how
the input variable is used in the rules. The
input values are shown here at the top.
This column of plots (blue)
shows how the output variable
is used in the rules.
This line provides a
defuzzified value.
The bottom-right plot
shows how the output of
each rule is combined to
make an aggregate
output and then
defuzzified.
Shift the plots left, right,
up, or down with these
buttons.
Slide this line to change
your input values, and
generate a new output
response.
2 Tutorial
2-60
under food, thereis a plot which is blank. This corresponds tothe
characterization of nonefor thevariablefood in thesecond rule. Thefourth
plot in thethirdcolumn of plots represents theaggregateweighteddecision for
thegiven inferencesystem. This decision will depend on theinput values for
thesystem.
Therearealsothenowfamiliar items likethestatus lineandthemenu bar. I n
thelower right thereis a text field intowhich you can enter specific input
values. For thetwo-input system, you will enter an input vector, [9 8], for
example, and then click on input. You can alsoadjust theseinput values by
clickinganywhereon any of thethreeplots for each input. This will movethe
red index linehorizontally, tothepoint whereyou haveclicked. You can also
just click and dragthis linein order tochangetheinput values. When you
releasetheline, (or after manually specifyingtheinput), a newcalculation is
performed, and you can seethewholefuzzy inferenceprocess takeplace.
Wheretheindex linerepresentingservicecrosses themembership function
lineserviceis poor in theupper left plot will determinethedegreetowhich
ruleoneis activated. A yellowpatch of color under theactual membership
function curveis used tomakethefuzzy membershipvaluevisually apparent.
Each of thecharacterizations of each of thevariables is specified with respect
totheinput index linein this manner. I f wefollowrule1 across thetop of the
diagram, wecanseetheconsequent tipischeaphasbeentruncatedtoexactly
thesamedegreeas the(composite) antecedentthis is theimplication process
in action. Theaggregation occurs down thethird column, and theresultant
aggregateplot is shown in thesingleplot tobefound in thelower right corner
of theplot field. Thedefuzzifiedoutput valueisshown bythethick linepassing
through theaggregatefuzzy set.
TheRuleViewer allows you tointerpret theentirefuzzy inferenceprocess at
once. TheRuleViewer alsoshows howtheshapeof certain membership
functions influences theoverall result. Sinceit plots every part of every rule, it
can becomeunwieldy for particularly largesystems, but, for a relatively small
number of inputsandoutputs, it performswell (dependingonhowmuchscreen
spaceyou devotetoit) with up to30 rules and as many as 6 or 7 variables.
TheRuleViewer shows onecalculation at a timeand in great detail. I n this
sense, it presentsasort of microviewof thefuzzyinferencesystem. I f you want
toseetheentireoutput surfaceof your system, that is, theentirespan of the
output set based on theentirespan of theinput set, you need toopen up the
SurfaceViewer. This is thelast of our fivebasic GUI tools in theFuzzy Logic
Toolbox, and you open it by selecting Viewsurface... fromtheViewmenu.
Building Systems with the Fuzzy Logic Toolbox
2-61
The Surface Viewer
Upon openingtheSurfaceViewer, wearepresented with a two-dimensional
curvethat represents themappingfromservicequality totip amount. Since
this is a one-input one-output case, wecan seetheentiremappingin oneplot.
Two-input one-output systems alsowork well, as they generate
three-dimensional plots that MATLAB can adeptly manage. When wemove
beyond threedimensions overall, westart toencounter troubledisplayingthe
results. Accordingly, theSurfaceViewer is equipped with pop-up menus that
let you select any twoinputs and any oneoutput for plotting. J ust belowthe
pop-upmenus aretwotext input fields that let you determinehowmanyx-axis
and y-axis grid lines you want toinclude. This allows you tokeep the
calculation timereasonablefor complex problems. PushingtheEvaluate
button initiates thecalculation, and theplot comes up soon after the
calculation is complete. Tochangethex-axis or y-axis grid after thesurfaceis
The menu items allow
you to save, open, or
edit a fuzzy system
using any of the five
basic GUI tools.
These edit fields let
you determine how
densely to grid the
input space.
These pop-up menus
let you specify the
one or two displayed
input variables.
This edit field lets you
set the input explicitly
for inputs not specified
in the surface plot.
This status line describes the most recent operation.
Use mouse to rotate the axes.
This plot shows the
output surface for any
output of the system
versus any one or two
inputs to the system
This pop-up menu lets
you specify the
displayed output
variable.
Push this button when
youre ready to
calculate and plot.
The Help button gives
some information
about how the Surface
Viewer works, and the
Close button closes the
window.
2 Tutorial
2-62
in view, simply changetheappropriatetext field, and click on either X-grids:
or Y-grids:, accordingtowhich text field you changed, toredrawtheplot.
TheSurfaceViewer has a special capability that is very helpful in cases with
two(or more) inputs and oneoutput: you can actually grab theaxes and
reposition themtoget adifferent three-dimensional viewon thedata. TheRef.
Input: field is used in situations when therearemoreinputs required by the
systemthan thesurfaceis mapping. Supposeyou haveafour-input one-output
systemand would liketoseetheoutput surface. TheSurfaceViewer can
generateathree-dimensional output surfacewhereanytwoof theinputs vary,
but twoof theinputs must beheld constant sincecomputer monitors cannot
display a five-dimensional shape. I n such a casetheinput would bea
four-dimensional vector withNaNsholdingtheplaceof thevaryinginputswhile
numerical values would indicatethosevalues that remain fixed. An NaN is the
I EEE symbol for not a number.
This concludes thequick walk-through of each of themain GUI tools. Notice
that for thetippingproblem, theoutput of thefuzzy systemmatches our
original idea of theshapeof thefuzzy mappingfromservicetotip fairly well.
I n hindsight, you might say, Why bother? I could havejust drawn a quick
lookup tableand been donean hour ago!However, if you areinterested in
solvingan entireclass of similar decision-makingproblems, fuzzy logic may
providean appropriatetool for thesolution, given its easewith which asystem
can bequickly modified.
Importing and Exporting from the GUI Tools
When you savea fuzzy systemtodisk, youresavingan ASCI I text FI S file
representation of that systemwith thefilesuffix .fis. This text filecan be
edited and modified and is simpletounderstand. When you saveyour fuzzy
systemtotheMATLAB workspace, yourecreatingavariable(whosenameyou
choose) that will act as a MATLAB structurefor theFI S system. FI S files and
FI S structures represent thesamesystem.
Note: I f you donot saveyour FI S toyour disk, but only saveit tothe
MATLAB workspace, you will not beabletorecover it for usein a new
MATLAB session.
Building Systems with the Fuzzy Logic Toolbox
2-63
Customizing Your Fuzzy System
I f you want toincludecustomized functions as part of your useof theFuzzy
LogicToolbox, thereareafewguidelines you needtofollow. TheAND method,
OR method, aggregation method, and defuzzification method functions you
provideneedtowork in asimilar way tomax, min, or prod in MATLAB. That is,
they must beabletooperatedown thecolumns of a matrix. For example, the
implication method does an element by element matrix operation, similar to
themin function, as in
a=[1 2; 3 4];
b=[2 2; 2 2];
min(a,b)
ans =
1 2
2 2
Custom Membership Functions
You can createyour own membership functions usingan M-file. Thevalues
thesefunctions can takemust bebetween 0 and 1. Thereis a limitation on
customized membership functions in that they cannot usemorethan 16
parameters.
Todefinea custommembership function named custmf:
1 Createan M-filefor a function, custmf.m, that takes values between 0 and
1, and depends on at most 16 parameters.
2 ChoosetheAdd CustomMF itemin theEdit menu on theMembership
Function Editor GUI .
3 Enter your custommembership function M-filename, custmf, in theM-file
function nametext box.
4 Enter thevector of parameters you want tousetoparameterizeyour
customized membership function in thetext box next toParameter list.
5 Givethecustommembership function a namedifferent fromany other
membership function nameyou will usein your FI S.
6 Select OK.
2 Tutorial
2-64
Hereis somesamplecodefor a custommembership function, testmf1, that
depends on eight parameters between 0 and 10.
function out = testmf1(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);
else
y(i)=0;
end
end
out=.1*y';
You can try namingthis filetestmf1.m and loadingit intotheMembership
Function Editor usingtheparameters of your choice.
Working from the Command Line
2-65
Working from the Command Line
Thetippingexamplesystemis oneof many examplefuzzy inferencesystems
provided with theFuzzy Logic Toolbox. TheFI S is always cast as a MATLAB
structure. Toload this system(rather than botheringwith creatingit from
scratch), type
a = readfis('tipper.fis')
MATLAB will respond with
a =
name: 'tipper'
type: 'mamdani'
andMethod: 'min'
orMethod: 'max'
defuzzMethod: 'centroid'
impMethod: 'min'
aggMethod: 'max'
input: [1x2 struct]
output: [1x1 struct]
rule: [1x3 struct]
Thelabels on theleft of this listingrepresent thevarious components of the
MATLAB structureassociated with tipper.fis. You can access thevarious
components of this structureby typingthecomponent nameafter typinga. At
theMATLAB command line, type
a.type
for example. MATLAB will respond with
ans =
mamdani
Thefunction
getfis(a)
returns almost thesamestructureinformation that typing a, alonedoes.
getfis(a) returns
Name = tipper
Type = mamdani
2 Tutorial
2-66
NumInputs = 2
InLabels =
service
food
NumOutputs = 1
OutLabels =
tip
NumRules = 3
AndMethod = min
OrMethod = max
ImpMethod = min
AggMethod = max
DefuzzMethod = centroid
Noticethat someof thesefields arenot part of thestructure, a. Thus, you
cannot get information by typing a.Inlabels, but you can get it by typing:
getfis(a,'Inlabels')
Similarly, you can obtain structureinformation usinggetfis in this manner.
getfis(a,'input',1)
getfis(a,'output',1)
getfis(a,'input',1,'mf',1)
Thestructure.field syntax alsogenerates this information. For more
informationonthesyntaxfor MATLAB structures, seeChapter 13, Structures
and Cell Arrays,in UsingMATLAB.
For example, type
a.input
or
a.input(1).mf(1)
Thefunction getfis is loosely modeledon theHandleGraphics

function get.
Thereis alsoa function called setfis that acts as thereciprocal togetfis. I t
allows you tochangeany property of an FI S. For example, if you wanted to
changethenameof this system, you could type
a = setfis(a,'name','gratuity');
Working from the Command Line
2-67
However, sincea is already aMATLAB structure, you can set this information
moresimply by typing
a.name = 'gratuity';
NowtheFI S structurea has been changedtoreflect thenewname. I f you want
a littlemoreinsight intothis FI S structure, try
showfis(a)
This returns a printout listingall theinformation about a. This function is
intended morefor debuggingthan anythingelse, but it shows all the
information recorded in theFI S structure
Sincethevariable, a, designates thefuzzy tippingsystem, you can call upany
of theGUI s for thetippingsystemdirectly fromthecommand line. Any of the
followingwill bringup thetippingsystemwith theassociated GUI .
fuzzy(a): brings up theFI S Editor
mfedit(a): brings up theMembership Function Editor
ruleedit(a): brings up theRuleEditor
ruleview(a): brings up the RuleViewer
surfview(a): brings up the SurfaceViewer
I f, in addition, a is a Sugeno-typeFI S, then anfisedit(a) will bringup the
ANFI S Editor GUI .
Onceany of theseGUI s has been opened, you can access any of theother GUI s
usingthepull-down menu rather than thecommand line.
System Display Functions
Therearethreefunctions designed togiveyou a high-level viewof your fuzzy
inferencesystemfromthecommand line: plotfis, plotmf, and gensurf. The
2 Tutorial
2-68
first of thesedisplays thewholesystemas a block diagrammuch as it would
appear on theFI S Editor.
plotfis(a)
After closingany open MATLAB figures or GUI windows, thefunction plotmf
plots all themembership functions associated with a given variableas follows:
plotmf(a,'input',1)
returns
Working from the Command Line
2-69
plotmf(a,'output',1)
Theseplots will appear in theMembershipFunction Editor GUI , or in an open
MATLAB figure, if plotmf is called whileeither of theseis open.
0 1 2 3 4 5 6 7 8 9 10
0
0.2
0.4
0.6
0.8
1
service
D
e
g
r
e
e

o
f

m
e
m
b
e
r
s
h
i
p
poor good excellent
0 5 10 15 20 25 30
0
0.2
0.4
0.6
0.8
1
tip
D
e
g
r
e
e

o
f

m
e
m
b
e
r
s
h
i
p
cheap average generous
2 Tutorial
2-70
Finally, thefunction gensurf will plot any oneor twoinputs versus any one
output of a given system. Theresult is either a two-dimensional curve, or a
three-dimensional surface. Notethat when therearethreeor moreinputs,
gensurf must begeneratedwith all but twoinputs fixed, as is describedin the
description of genfis in Chapter 3, Reference .
gensurf(a)
Building a System from Scratch
I t is possibletousetheFuzzy Logic Toolbox without botheringwith theGUI
tools at all. For instance, tobuild thetippingsystementirely fromthe
command line, you would usethecommands newfis, addvar, addmf, and
addrule.
Probably thetrickiest part of this process is learningtheshorthand that the
fuzzy inferencesystems usefor buildingrules. This is accomplished usingthe
command linefunction, addrule.
Each variable, input, or output, has an index number, and each membership
function has an index number. Therules arebuilt fromstatements likethis
if input1 is MF1 or input2 is MF3 then output1 is MF2 (weight =0.5)
This ruleis turnedintoastructureaccordingtothefollowinglogic: I f thereare
minputs toa systemand n outputs, then thefirst mvector entries of therule
structurecorrespondtoinputs 1through m. Theentry in column 1is theindex
number for themembership function associated with input 1. Theentry in
0
2
4
6
8
10
0
2
4
6
8
10
5
10
15
20
25
service
food
t
i
p
Working from the Command Line
2-71
column 2 is theindex number for themembership function associated with
input 2. And soon. Thenext n columns work thesameway for theoutputs.
Column m+n +1 is theweight associated with that rule(typically 1) and
column m+n +2 specifies theconnectiveused (whereAND =1 and OR =2).
Thestructureassociated with theruleshown aboveis
1 3 2 0.5 2
Hereis oneway you can build theentiretippingsystemfromthecommand
line, usingtheMATLAB structuresyntax.
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';
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';
2 Tutorial
2-72
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, hereis howyou can build theentiretippingsystemfromthe
command lineusingFuzzy Logic Toolbox commands.
a=newfis('tipper');
a=addmf(a,'input',1,'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);
Working from the Command Line
2-73
FIS Evaluation
Toevaluatetheoutput of a fuzzy systemfor a given input, usethefunction
evalfis. For example, thefollowingscript evaluates tipper at theinput, [12].
a = readfis('tipper');
evalfis([1 2], a)
ans =
5.5586
This function can alsobeusedfor multiplecollections of inputs, sincedifferent
input vectorsarerepresentedindifferent partsof theinput structure. Bydoing
multipleevaluations at once, you get a tremendous boost in speed.
evalfis([3 5; 2 7], a)
ans =
12.2184
7.7885
The FIS Structure
TheFI S structureis theMATLAB object that contains all thefuzzy inference
systeminformation. This structureis stored insideeach GUI tool. Access
functions such as getfis and setfis makeit easy toexaminethis structure.
You can alsoaccess theFI S structureinformation usingthestructure.field
syntax (seethesection, WorkingfromtheCommand Line on page2-65).
All theinformation for a given fuzzy inferencesystemis contained in theFI S
structure, includingvariablenames, membership function definitions, and so
2 Tutorial
2-74
on. Thisstructurecanitself bethought of asahierarchyof structures, asshown
in thediagrambelow:
You can generatea listingof information on theFI S usingtheshowfis
command, as shown below.
showfis(a)
1. Name tipper
2. Type mamdani
3. Inputs/Outputs [ 2 1 ]
4. NumInputMFs [ 3 2 ]
5. NumOutputMFs 3
6. NumRules 3
7. AndMethod min
8. OrMethod max
9. ImpMethod min
10. AggMethod max
11. DefuzzMethod centroid
12. InLabels service
13. food
14. OutLabels tip
FIS
name
type
andMethod
orMethod
defuzzMethod
impMethod
aggMethod
input
output
rule
input
name
range
mf
rules
antecedent
consequent
weight
connections
input1MFs
name
type
params
output MFs
name
type
params
output
name
range
mf
input2MFs
name
type
params
Working from the Command Line
2-75
15. InRange [ 0 10 ]
16. [ 0 10 ]
17. OutRange [ 0 30 ]
18. InMFLabels poor
19. good
20. excellent
21. rancid
22. delicious
23. OutMFLabels cheap
24. average
25. generous
26. InMFTypes gaussmf
27. gaussmf
28. gaussmf
29. trapmf
30. trapmf
31. OutMFTypes trimf
32. trimf
33. trimf
34. InMFParams [ 1.5 0 0 0 ]
35. [ 1.5 5 0 0 ]
36. [ 1.5 10 0 0 ]
37. [ 0 0 1 3 ]
38. [ 7 9 10 10 ]
39. OutMFParams [ 0 5 10 0 ]
40. [ 10 15 20 0 ]
41. [ 20 25 30 0 ]
42. Rule Antecedent [ 1 1 ]
43. [ 2 0 ]
44. [ 3 2 ]
42. Rule Consequent 1
43. 2
44. 3
42. Rule Weigth 1
43. 1
44. 1
42. Rule Connection 2
43. 1
44. 2
2 Tutorial
2-76
Thelist of command linefunctions associated with FI S construction include
getfis, setfis, showfis, addvar, addmf, addrule, rmvar, and rmmf.
Saving FIS Files on Disk
A specialized text fileformat is used for savingfuzzy inferencesystems toa
disk. Thefunctions readfis and writefis areused for readingand writing
thesefiles.
I f you prefer, you can modify theFI S by editingits .fis text filerather than
usingany of theGUI s. You shouldbeaware, however, that changingoneentry
may obligeyou tochangeanother. For example, if you deletea membership
function usingthis method, you alsoneed tomakecertain that any rules
requiringthis membership function arealsodeleted.
Therules appear in indexedformat in a .fis text file. Hereis thefile
tipper.fis.
[System]
Name='tipper'
Type='mamdani'
NumInputs=2
NumOutputs=1
NumRules=3
AndMethod='min'
OrMethod='max'
ImpMethod='min'
AggMethod='max'
DefuzzMethod='centroid'
[Input1]
Name='service'
Range=[0 10]
NumMFs=3
MF1='poor':'gaussmf',[1.5 0]
MF2='good':'gaussmf',[1.5 5]
MF3='excellent':'gaussmf',[1.5 10]
[Input2]
Name='food'
Range=[0 10]
NumMFs=2
Working from the Command Line
2-77
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 Tutorial
2-78
Working with Simulink
TheFuzzy Logic Toolbox is designed towork seamlessly with Simulink, the
simulation softwareavailablefromTheMathWorks. Onceyouvecreatedyour
fuzzy systemusingtheGUI tools or someother method, youreready toembed
your systemdirectly intoa simulation.
An Example: Water Level Control
Picturea tank with a pipeflowingin and a pipeflowingout. You can change
thevalvecontrollingthewater that flows in, but theoutflowratedepends on
thediameter of theoutflowpipe(which is constant) and thepressurein the
tank (which varies with thewater level). Thesystemhas somevery nonlinear
characteristics.
A controller for thewater level in thetank needs toknowthecurrent water
level and it needs tobeabletoset thevalve. Our controllers input will bethe
water level error (desired water level minus actual water level) and its output
will betherateat which thevalveis openingor closing. A first pass at writing
a fuzzy controller for this systemmight bethefollowing.
1. I f (level is okay) then (valveis no_change) (1)
2. I f (level is low) then (valveis open_fast) (1)
3. I f (level is high) then (valveis close_fast) (1)
Oneof thegreat advantages of theFuzzy Logic Toolbox is theability totake
fuzzy systems directly intoSimulink and test themout in a simulation
environment. A Simulink block diagramfor this systemis shown below. I t
Working with Simulink
2-79
contains a Simulink block called theFuzzy Logic Controller block. The
Simulink block diagramfor this systemis sltank. Typing
sltank
at thecommand line, causes thesystemtoappear.
At thesametime, thefiletank.fis is loaded intotheFI S structuretank.
2 Tutorial
2-80
Someexperimentation shows that threerules arenot sufficient, sincethe
water level tendstooscillatearoundthedesiredlevel. Thisisseenfromtheplot
below.
Weneed toadd another input, thewater levels rateof change, toslowdown
thevalvemovement when weget closetotheright level.
4. I f (level is good) and (rateis negative) then (valveis close_slow) (1)
5. I f (level is good) and (rateis positive) then (valveis open_slow) (1)
Thedemo, sltank is built with thesefiverules. You can examineWith all five
rules in operations, thestep responseby simulatingthis system. This is done
by clickingon Start fromthepull-down menu under Simulate, andclickingon
theComparison block. Theresult looks likethis
Oneinterestingfeatureof thewater tank systemisthat thetank emptiesmuch
moreslowlythan it fills upbecauseof thespecificvalueof theoutflowdiameter
pipe. Wecan deal with this by settingtheclose_slowvalvemembership
function tobeslightly different fromtheopen_slowsetting. A PI D controller
does not havethis capability. Thevalvecommand versus thewater level
0 10 20 30 40 50 60 70 80 90 100
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
Time (second)
0 10 20 30 40 50 60 70 80 90 100
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
Time (second)
Working with Simulink
2-81
changerate(depicted as water) and therelativewater level change(depicted
as level) surfacelooks likethis. I f you look closely, you can seea slight
asymmetry totheplot.
BecausetheMATLAB technical computingenvironment supports somany
tools (liketheControl SystemToolbox, theNeural Network Toolbox, the
Nonlinear Control Design Blockset, and soon), you can, for example, easily
makea comparison of a fuzzy controller versus a linear controller or a neural
network controller.
For a demonstration of howtheRuleViewer can beused tointeract with a
Fuzzy Logic Controller block in a Simulink model, type
sltankrule
Thisdemocontainsablock calledtheFuzzyController WithRuleViewer block.
I n this demo, theRuleViewer opens when you start theSimulink simulation.
This RuleViewer provides an animation of howtherules arefired duringthe
1
0.5
0
0.5
1
0.1
0.05
0
0.05
0.1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
level
water
v
a
l
v
e
2 Tutorial
2-82
water tank simulation. Thewindows that open when you simulatethe
sltankrule demoaredepicted as follows:
TheRuleViewer that opens duringthesimulation can beused toaccess the
Membership Function Editor, theRuleEditor, or any of theother GUI s, (see
TheMembershipFunction Editoron page2-52, or TheRuleEditoron page
2-56, for moreinformation).
Working with Simulink
2-83
For example, youmaywant toopentheRuleEditor tochangeoneof your rules.
Todoso, select theEdit rules menu itemunder theViewmenu of theopen
RuleViewer. Nowyou can viewor edit therules for this Simulink model:
I ts best if you stop thesimulation prior toselectingany of theseeditors to
changeyour FI S. Remember tosaveany changes you maketoyour FI S tothe
workspacebeforeyou restart thesimulation.
Building Your Own Fuzzy Simulink Models
Tobuildyour ownSimulink systemsthat usefuzzylogic, simplycopytheFuzzy
Logic Controller block out of sltank (or any of theother Simulink demo
systemsavailablewiththetoolbox) andplaceit inyour ownblock diagram. You
can alsoopen theSimulink library called fuzblock, which contains theFuzzy
Logic Controller block, theFuzzy Controller With RuleViewer block, and
several demoblocks. Toaccess theseblocks, type
fuzblock
2 Tutorial
2-84
at theMATLAB prompt. Thefollowinglibrary appears:
When you usetheseblocks, makesurethat thefuzzy inferencesystem(FI S)
structurecorrespondingtoyour fuzzy systemis both in theMATLAB
workspace, andreferredtobynameinthedialogboxassociatedwith theFuzzy
Logic Controller block.
Double-click ontheFuzzyController WithRuleViewer block, andthefollowing
appears:
This block uses thezero-order hold method for sampling.
TheFuzzy Logic Controller block is a masked Simulink block based on the
S-function sffis.mex. This function is itself based on thesamealgorithms as
thefunction evalfis, but it has been tailored towork optimally within the
Working with Simulink
2-85
Simulink environment. For moredescriptions of these, seefuzblock on page
3-27, and sffis on page3-65.
2 Tutorial
2-86
Sugeno-Type Fuzzy Inference
Thefuzzy inferenceprocess wevebeen referringtosofar is known as
Mamdanis fuzzy inferencemethod. I ts themost commonly seen fuzzy
methodology. I n this section wediscuss theso-called Sugeno, or
Takagi-Sugeno-Kangmethod of fuzzy inferencefirst introduced in 1985
[Sug85]. I t issimilar totheMamdani methodin manyrespects. I n fact thefirst
twoparts of thefuzzy inferenceprocess, fuzzifyingtheinputs andapplyingthe
fuzzy operator, areexactly thesame. Themain differencebetween
Mamdani-typeof fuzzy inferenceand Sugeno-typeis that theoutput
membership functions areonly linear or constant for Sugeno-typefuzzy
inference.
A typical fuzzy rulein a zero-order Sugenofuzzy model has theform
if x is A and y is B then z =k
whereA and B arefuzzy sets in theantecedent, whilek is a crisply defined
constant intheconsequent. Whentheoutput of eachruleisaconstant likethis,
thesimilaritywithMamdanismethodisstriking. Theonlydistinctionsarethe
fact that all output membership functions aresingleton spikes, and the
implication and aggregation methods arefixed and can not beedited. The
implication methodis simply multiplication, andtheaggregation operator just
includes all of thesingletons.
Sugeno-Type Fuzzy Inference
2-87
Thefigureaboveshows thefuzzy tippingmodel developedin previous sections
of this manual adaptedfor useas azero-order Sugenosystem. Fortunatelyit is
frequentlythecasethat singletonoutput functionsarecompletelysufficient for
a given problems needs. As an example, thesystemtippersg.fis is the
Sugeno-typerepresentation of thenow-familiar tippingmodel. I f you load the
5. Defuzzify
(weighted
average)
4. Apply
aggregation
method (max).
2. Apply
fuzzy
operation
(OR =max)
1. Fuzzify inputs
3. Apply
implication
method (min).
delicious
average
good
excellent
rancid cheap poor
generous
food = 8
input 2 output
rule 2 has
no dependency
on input 2
tip = 16.3%
service = 3
input 1
If service is poor food is rancid tip =cheap then or
If service is good then tip =average
If service is excellent food is delicious then or tip =generous
1.
2.
3.
2 Tutorial
2-88
systemand plot its output surface, you will seeit is almost thesameas the
Mamdani systemwevebeen lookingat.
a = readfis('tippersg');
gensurf(a)
Themoregeneral first-order Sugenofuzzy model has rules of theform
if x is A and y is B then z =p*x +q*y +r
whereA and B arefuzzy sets in theantecedent, whilep, q, and r areall
constants. Theeasiest waytovisualizethefirst-order systemistothink of each
ruleas definingthelocation of a movingsingleton.That is, thesingleton
output spikes can movearound in a linear fashion in theoutput space,
dependingon what theinput is. This alsotends tomakethesystemnotation
verycompact andefficient. Higher order Sugenofuzzymodels arepossible, but
they introducesignificant complexity with littleobvious merit. Sugenofuzzy
modelswhoseoutput membershipfunctionsaregreater thanfirst order arenot
supported by theFuzzy Logic Toolbox.
Becauseof thelinear dependenceof each ruleon thesystems input variables,
theSugenomethodisideal for actingasaninterpolatingsupervisor of multiple
linear controllers that aretobeapplied, respectively, todifferent operating
conditions of a dynamicnonlinear system. For example, theperformanceof an
aircraft may changedramatically with altitudeand Mach number. Linear
controllers, though easy tocomputeand well-suited toany given flight
condition, must beupdated regularly and smoothly tokeep up with the
changingstateof theflight vehicle. A Sugenofuzzy inferencesystemis
0
2
4
6
8
10
0
2
4
6
8
10
10
15
20
service
food
t
i
p
Sugeno-Type Fuzzy Inference
2-89
extremely well suited tothetask of smoothly interpolatingthelinear gains
that would beapplied across theinput space; its a natural and efficient gain
scheduler. Similarly, aSugenosystemissuitedfor modelingnonlinear systems
by interpolatingmultiplelinear models.
An Example: Two Lines
Toseeaspecificexampleof asystemwithlinear output membershipfunctions,
consider theoneinput oneoutput systemstored in sugeno1.fis.
fismat = readfis('sugeno1');
getfis(fismat,'output',1)
Name = output
NumMFs = 2
MFLabels =
line1
line2
Range = [0 1]
Theoutput variablehas twomembership functions:
getfis(fismat,'output',1,'mf',1)
Name = line1
Type = linear
Params =
1 1
getfis(fismat,'output',1,'mf',2)
Name = line2
Type = linear
Params =
1 1
Further, thesemembershipfunctionsarelinear functionsof theinput variable.
Themembership function line1 is defined by theequation
output =(-1)*input +(-1)
and themembership function line2 is defined by theequation
output =(1)*input +(-1)
2 Tutorial
2-90
Theinput membership functions and rules definewhich of theseoutput
functions will beexpressed and when.
showrule(fismat)
ans =
1. If (input is low) then (output is line1) (1)
2. If (input is high) then (output is line2) (1)
Thefunction plotmf shows us that themembership function low generally
refers toinput values less than zero, whilehigh refers tovalues greater than
zero. Thefunction gensurf showshowtheoverall fuzzysystemoutput switches
smoothly fromthelinecalled line1 tothelinecalled line2.
subplot(2,1,1), plotmf(fismat,'input',1)
subplot(2,1,2), gensurf(fismat)
This is just oneexampleof howaSugeno-typesystemgives you thefreedomto
incorporatelinear systems intoyour fuzzy systems. By extension, you could
build a fuzzy systemthat switches between several optimal linear controllers
as a highly nonlinear systemmoves around in its operatingspace.
Conclusion
Becauseit isamorecompact andcomputationallyefficient representationthan
a Mamdani system, theSugenosystemlends itself totheuseof adaptive
techniques for constructingfuzzy models. Theseadaptivetechniques can be
used tocustomizethemembership functions sothat thefuzzy systembest
models thedata.
5 4 3 2 1 0 1 2 3 4 5
0
0.2
0.4
0.6
0.8
1
input
D
e
g
r
e
e

o
f

b
e
l
i
e
f
low high
5 4 3 2 1 0 1 2 3 4 5
1
0
1
2
3
4
input
o
u
t
p
u
t
Sugeno-Type Fuzzy Inference
2-91
Note on FIS Conversion: TheMATLAB command linefunction mam2sug can
beused toconvert a Mamdani systemintoa Sugenosystem(not necessarily
with a singleoutput) with constant output membership functions. I t uses the
centroid associated with all of theoutput membership functions of the
Mamdani system. SeeChapter 3 for details.
Herearesomefinal considerations about thetwodifferent methods:
Advantages of the Sugeno method
I ts computationally efficient.
I t works well with linear techniques (e.g., PI D control).
I t works well with optimization and adaptivetechniques.
I t has guaranteed continuity of theoutput surface.
I ts well-suited tomathematical analysis.
Advantages of the Mamdani method
I ts intuitive.
I t has widespread acceptance.
I ts well-suited tohuman input.
2 Tutorial
2-92
anfis and the ANFIS Editor GUI
Thebasic structureof thetypeof fuzzy inferencesystemthat weveseen thus
far is a model that maps input characteristics toinput membership functions,
input membership function torules, rules toa set of output characteristics,
output characteristics tooutput membership functions, and theoutput
membership function toa single-valued output or a decision associated with
theoutput. Wehaveonly considered membership functions that havebeen
fixed, and somewhat arbitrarily chosen. Also, weveonly applied fuzzy
inferencetomodelingsystems whoserulestructureis essentially
predetermined by theusers interpretation of thecharacteristics of the
variables in themodel.
I n this section wediscuss theuseof thefunction anfis and theANFI S Editor
GUI in theFuzzy Logic Toolbox. Thesetools apply fuzzy inferencetechniques
todata modeling. As you haveseen fromtheother fuzzy inferenceGUI s, the
shapeof themembership functions depends on parameters, and changing
theseparameterswill changetheshapeof themembershipfunction. I nsteadof
just lookingat thedatatochoosethemembershipfunction parameters, wewill
seehowmembership function parameters can bechosen automatically using
theseFuzzy Logic Toolbox applications.
A Modeling Scenario
Supposeyou want toapply fuzzy inferencetoa systemfor which you already
havea collection of input/output data that you would liketousefor modeling,
model-following, or somesimilar scenario. You dont necessarily havea
predetermined model structurebased on characteristics of variables in your
system.
Therewill besomemodelingsituations in which you cant just look at thedata
and discern what themembership functions should look like. Rather than
choosingtheparameters associated with a given membership function
arbitrarily, theseparameters could bechosen soas totailor themembership
functions totheinput/output data in order toaccount for thesetypes of
variations in thedata values. This is wheretheso-called neuro-adaptive
learningtechniques incorporated intoanfis in theFuzzy Logic Toolbox can
help.
anfis and the ANFIS Editor GUI
2-93
Model Learning and Inference Through ANFIS
Thebasicideabehindtheseneuro-adaptivelearningtechniquesisverysimple.
Thesetechniques providea method for thefuzzy modelingprocedureto learn
information about a data set, in order tocomputethemembership function
parameters that best allowtheassociated fuzzy inferencesystemtotrack the
given input/output data. This learningmethod works similarly tothat of
neural networks. TheFuzzy Logic Toolbox function that accomplishes this
membership function parameter adjustment is called anfis. anfis can be
accessed either fromthecommand line, or through theANFI S Editor GUI .
Sincethefunctionality of thecommand linefunction anfis and theANFI S
Editor GUI is similar, they areused somewhat interchangeably in this
discussion, until wedistinguish themthrough thedescription of theGUI .
What Is ANFIS?
TheacronymANFI S derives its namefromadaptiveneuro-fuzzy inference
system. Usinga given input/output data set, thetoolbox function anfis
constructs a fuzzy inferencesystem(FI S) whosemembership function
parameters aretuned (adjusted) usingeither a backpropagation algorithm
alone, or in combination with a least squares typeof method. This allows your
fuzzy systems tolearn fromthedata they aremodeling.
FIS Structure and Parameter Adjustment
A network-typestructuresimilar tothat of a neural network, which maps
inputs through input membership functions and associated parameters, and
then through output membership functions and associated parameters to
outputs, can beused tointerpret theinput/output map.
Theparameters associated with themembership functions will change
through thelearningprocess. Thecomputation of theseparameters (or their
adjustment) is facilitated by a gradient vector, which provides a measureof
howwell thefuzzy inferencesystemis modelingtheinput/output data for a
given set of parameters. Oncethegradient vector is obtained, any of several
optimization routines could beapplied in order toadjust theparameters soas
toreducesomeerror measure(usually defined by thesumof thesquared
differencebetween actual and desired outputs). anfis uses either back
propagation or acombination of least squares estimation andbackpropagation
for membership function parameter estimation.
2 Tutorial
2-94
Familiarity Breeds Validation: Know Your Data
Themodelingapproach usedby anfis is similar tomany systemidentification
techniques. First, you hypothesizea parameterized model structure(relating
inputs tomembership functions torules tooutputs tomembership functions,
and soon). Next, you collect input/output data in a formthat will beusableby
anfis for training. You can then useanfis totrain theFI S model toemulate
thetrainingdata presented toit by modifyingthemembership function
parameters accordingtoa chosen error criterion.
I n general, this typeof modelingworks well if thetrainingdata presented to
anfis for training(estimating) membership function parameters is fully
representativeof thefeatures of thedata that thetrained FI S is intended to
model. This is not always thecase, however. I n somecases, data is collected
usingnoisy measurements, and thetrainingdata cannot berepresentativeof
all thefeatures of thedata that will bepresented tothemodel. This is where
model validation comes intoplay.
Model Validation Using Checking and Testing Data Sets
Model validation is theprocess by which theinput vectors frominput/output
data sets on which theFI S was not trained, arepresented tothetrained FI S
model, toseehowwell theFI S model predicts thecorrespondingdata set
output values. This is accomplished with theANFI S Editor GUI usingthe
so-called testingdata set, and its useis described in a subsection that follows.
You can alsouseanother typeof data set for model validation in anfis. This
other typeof validation dataset is referredtoas thecheckingdata set andthis
set is used tocontrol thepotential for themodel overfittingthedata. When
checkingdata is presented to anfis as well as trainingdata, theFI S model is
selectedtohaveparametersassociatedwiththeminimumcheckingdatamodel
error.
Oneproblemwith model validation for models constructed usingadaptive
techniques is selectinga data set that is both representativeof thedata the
trainedmodel isintendedtoemulate, yet sufficientlydistinct fromthetraining
data set soas not torender thevalidation process trivial. I f you havecollected
a largeamount of data, hopefully this data contains all thenecessary
representativefeatures, sotheprocess of selectinga data set for checkingor
testingpurposes is madeeasier. However, if you expect tobepresentingnoisy
measurements toyour model, its possiblethetrainingdata set does not
includeall of therepresentativefeatures you want tomodel.
anfis and the ANFIS Editor GUI
2-95
Thebasic idea behind usinga checkingdata set for model validation is that
after a certain point in thetraining, themodel begins overfittingthetraining
data set. I n principle, themodel error for thecheckingdata set tends to
decreaseas thetrainingtakes placeuptothepoint that overfittingbegins, and
then themodel error for thecheckingdata suddenly increases. I n thefirst
examplein thefollowingsection, twosimilar data sets areused for checking
andtraining, but thecheckingdataset iscorruptedbyasmall amount of noise.
This exampleillustrates of theuseof theANFI S Editor GUI with checking
datatoreducetheeffect of model overfitting. I n thesecondexample, atraining
data set that is presented toanfis is sufficiently different than theapplied
checkingdataset. By examiningthecheckingerror sequenceover thetraining
period, it is clear that thecheckingdata set is not good for model validation
purposes. Thisexampleillustratestheuseof theANFI S Editor GUI tocompare
data sets.
Some Constraints of anfis
anfis ismuchmorecomplexthanthefuzzyinferencesystemsdiscussedsofar,
and is not availablefor all of thefuzzy inferencesystemoptions. Specifically,
anfis only supports Sugeno-typesystems, and thesemust be:
First or zeroth order Sugeno-typesystems
Singleoutput, obtained usingweighted averagedefuzzification (linear or
constant output membership functions)
Of unity weight for each rule
An error occurs if your FI S structuredoes not comply with theseconstraints.
Moreover, anfis cannot accept all thecustomization options that basic fuzzy
inferenceallows. That is, you cannot makeyour own membership functions
and defuzzification functions; youll havetousetheones provided.
The ANFIS Editor GUI
Toget started with theANFI S Editor GUI , type
anfisedit
ThefollowingGUI will appear on your screen.
2 Tutorial
2-96
Fromthis GUI you can
Load data (training, testing, and checking) by selectingappropriateradio
buttons in theLoaddataportion of theGUI andthen selectingLoadData...
Theloaded data is plotted on theplot region.
Generatean initial FI S model or load an initial FI S model usingtheoptions
in theGenerateFIS portion of theGUI
ViewtheFI S model structureoncean initial FI S has been generated or
loaded by selectingtheStructurebutton
Test data against
the FIS model. The
plot appears in the
plot region.
Testing data appears on the
plot in blue as
Training data appears on
the plot in blue as
Checking data appears on
the plot in blue as
FIS output appears on the
plot in red as
..
o o
++
**
Load or save a fuzzy
Sugeno system, or open
new Sugeno system.
Undo
Open or edit a FIS with any
of the other GUIs.
Status of the number of inputs, outputs,
input membership functions, and output
membership functions
Load either training,
testing, or checking
data from disk or
workspace, or load
demo data. Data
appears in the plot
region.
Clear Data unloads the data set
selected under Type:
and clears the plot region.
Load FIS or generate FIS
from loaded data using
your chosen number of MFs
and rules or fuzzy.
After you generate
or load a FIS, this
button allows you to
open a graphical
representation of its
input/output
structure.
Train FIS after setting optimization
method, error tolerance, and number
of epochs. This generates error plots
in the plot region.
Plot region
anfis and the ANFIS Editor GUI
2-97
ChoosetheFI S model parameter optimizationmethod: backpropagationor a
mixtureof backpropagation and least squares (hybrid method)
Choosethenumber of trainingepochs and thetrainingerror tolerance
Train theFI S model by selectingtheTrain Nowbutton
This trainingadjusts themembership function parameters and plots the
training(and/or checkingdata) error plot(s) in theplot region.
ViewtheFI S model output versus thetraining, checking, or testingdata
output by selectingtheTest Nowbutton
This function plots thetest data against theFI S output in theplot region.
You can alsousetheANFI S Editor GUI menu bar toload an FI S training
initialization, saveyour trained FI S, open a newSugenosystem, or open any
of theother GUI s tointerpret thetrained FI S model.
Data Formalities and the ANFIS Editor GUI: Checking and Training
Tostart trainingan FI S usingeither anfis or theANFI S Editor GUI , first you
need tohavea trainingdata set that contains desired input/output data pairs
of thetarget systemtobemodeled. Sometimes you alsowant tohavethe
optional testingdata set that can check thegeneralization capability of the
resultingfuzzy inferencesystem, and/or a checkingdata set that helps with
model overfittingduringthetraining. Theuseof a testingdata set and a
checkingdata set for model validation is discussedin Model Validation Using
Checkingand TestingData Sets on page2-94. As wementioned previously,
overfittingis accounted for by testingtheFI S trained on thetrainingdata
against thecheckingdata, and choosingthemembership function parameters
tobethoseassociatedwith theminimumcheckingerror if theseerrorsindicate
model overfitting. You will havetoexamineyour trainingerror plots fairly
closely in order todeterminethis. Theseissues arediscussed later in an
example. Usually thesetrainingand checkingdata sets arecollected based on
observations of thetarget systemand arethen stored in separatefiles.
Note on Data Format: Any data set you load intotheANFI S Editor GUI , (or
that is appliedtothecommandlinefunction anfis) must bea matrix with the
input data arranged as vectors in all but thelast column. Theoutput data
must bein thelast column.
2 Tutorial
2-98
ANFIS Editor GUI Example 1: Checking Data Helps
Model Validation
I n this section welook at an examplethat loads similar trainingand checking
data sets, only thecheckingdata set is corrupted by noise.
Loading Data
Towork both of thefollowingexamples, you load thetrainingdata sets
(fuzex1trnData and fuzex2trnData) and thecheckingdata sets
(fuzex1chkData and fuzex2chkData), intotheANFI S Editor GUI fromthe
workspace. You may alsosubstituteyour own data sets.
Toload thesedata sets fromthedirectory fuzzydemos intotheMATLAB
workspace, type
load fuzex1trnData.dat
load fuzex2trnData.dat
load fuzex1chkData.dat
load fuzex2chkData.dat
fromthecommand line.
Note on loading data: You may alsowant toload your data set fromthe
fuzzydemos or any other directory on thedisk, usingtheANFI S Editor GUI ,
directly.
Open theANFI S Editor GUI by typinganfisedit. Toload thetrainingdata
set, click on Training, worksp. and then Load Data....
Thesmall GUI windowthat pops upallowsyoutotypein avariablenamefrom
theworkspace. Typein fuzex1trnData, as shown below.
anfis and the ANFIS Editor GUI
2-99
Thetrainingdataappears in theplot in thecenter of theGUI as aset of circles.
Noticethehorizontal axis is marked data set index. This index indicates the
rowfromwhich that input data valuewas obtained (whether or not theinput
is avector or ascalar). Next click on Checkingin theTypecolumn of theLoad
2 Tutorial
2-100
data portion of theGUI toload fuzex1chkData fromtheworkspace. This data
appears in theGUI plot as plusses superimposed on thetrainingdata.
This dataset will beusedtotrain afuzzy systemby adjustingthemembership
function parameters that best model this data. Thenext step is tospecify an
initial fuzzy inferencesystemfor anfis totrain.
Initializing and Generating Your FIS
You can either initializetheFI S parameters toyour own preference, or if you
donot haveany preferencefor howyou want theinitial membershipfunctions
tobeparameterized, you can let anfis dothis for you.
Automatic FIS Structure Generation with ANFIS
Toinitializeyour FI S usinganfis:
1 ChooseGrid partition, thedefault partitioningmethod. (Thetwopartition
methods, gridpartitioningandsubtractiveclustering, aredescribedlater in
+++ Checking data
ooo Training data
anfis and the ANFIS Editor GUI
2-101
Fuzzy C-Means Clusteringon page2-120, andin SubtractiveClustering
on page2-123.
2 Click on theGenerateFIS button. This brings up a menu fromwhich you
can choosethenumber of membershipfunctions, MFs, andthetypeof input
and output membership functions. Noticethereareonly twochoices for the
output membershipfunction: constant andlinear. Thislimitationof output
membershipfunction choicesisbecauseanfis onlyoperateson Sugeno-type
systems.
3 Fill in theentries as wevedonebelow, and click on OK.
You can alsoimplement this FI S generation fromthecommand lineusingthe
command genfis1 (for grid partitioning) or genfis2 (for subtractive
clustering). A command linelanguageexampleillustratingtheuseof genfis1
and anfis is provided later.
Specifying Your Own Membership Functions for ANFIS
Although wedont expect you todothis for this example, you can chooseyour
own preferred membership functions with specific parameters tobeused by
anfis as an initial FI S for training.
2 Tutorial
2-102
Todefineyour own FI S structureand parameters:
1 Open theEdit membership functions menu itemfromtheViewmenu.
2 Addyour desiredmembershipfunctions(thecustommembershipoptionwill
bedisabled for anfis). Theoutput membership functions must either beall
constant or all linear. For carryingout this and thefollowingstep, seeThe
FI S Editor on page2-49 and TheMembership Function Editoron page
2-52.
3 Select theEdit rules menu itemin theViewmenu. UsetheRuleEditor to
generatetherules (seeTheRuleEditoron page2-56).
4 Select theEdit FISpropertiesmenu itemfromtheViewmenu. Nameyour
FI S, and saveit toeither theworkspaceor thedisk.
5 UsetheViewmenu toreturn totheANFI S Editor GUI totrain theFI S.
Toload an existingFI S for ANFI S initialization, in theGenerateFIS portion
of theGUI , click on Loadfromworksp. or Loadfromdisk. You will loadyour
FI S fromthedisk if you havesaved an FI S previously that you would liketo
use. Otherwiseyou will beloadingyour FI S fromtheworkspace. Either of
theseradiobuttons toggletheGenerateFIS button toLoad.... Load your FI S
by clickingon this button.
anfis and the ANFIS Editor GUI
2-103
Viewing Your FIS Structure
After you generatetheFI S, you canviewthemodel structurebyclickingon the
Structurebutton in themiddleof theright-hand sideof theGUI . A newGUI
appears, as follows:
Thebranches in this nodal graph arecolor coded toindicatewhether or not
and, not, or or, areused in therules. Clickingon thenodes indicates
information about thestructure.
You can viewthemembership functions or therules by openingeither the
Membership Function Editor, or theRuleEditor fromtheViewmenu.
Return to other open GUIs
using the Window menu.
Node representing a normalization
factor for the rules.
Color coding of branches
characterizes the rules.
Node labels - for
example, leftmost
node is the
input node
2 Tutorial
2-104
ANFIS Training
Thetwoanfis parameter optimization method options availablefor FI S
trainingarehybrid (thedefault, mixed least squares and backpropagation)
and backpropa (backpropagation). TheError Toleranceis used tocreatea
trainingstoppingcriterion, which is related totheerror size. Thetrainingwill
stopafter thetrainingdataerror remainswithinthistolerance. Thisisbest left
set to0 if you dont knowhowyour trainingerror is goingtobehave.
Tostart thetraining:
Leavetheoptimization method at hybrid.
Set thenumber of trainingepochsto40, under theEpochslistingontheGUI
(thedefault valueis 3).
Select Train Now.
Thefollowingshould appear on your screen:
Noticehowthecheckingerror decreases up toa certain point in thetraining
and then it increases. This increaserepresents thepoint of model overfitting.
anfis chooses themodel parameters associated with theminimumchecking
***
Training error
... Checking error
anfis and the ANFIS Editor GUI
2-105
error (just prior tothis jump point). This is an examplefor which thechecking
data option of anfis is useful.
Testing Your Data Against the Trained FIS
Totest your FI S against thecheckingdata, click on Checkingdatain theTest
FISportionof theGUI , andclick onTest Now. Nowwhenyoutest thechecking
data against theFI S it looks pretty good:
Note on loading more data with anfis: I f you areever loadingdata into
anfis after clearingpreviously loaded data, you must makesurethat the
newly loaded data sets havethesamenumber of inputs as thepreviously
loaded ones did. Otherwiseyou will havetostart a newanfisedit session
fromthecommand line.
2 Tutorial
2-106
Note on the Checking Data option and Clearing Data: I f you dont want to
usethecheckingdata option of anfis, dont load any checkingdata beforeyou
train theFI S. I f you decidetoretrain your FI S with nocheckingdata, you can
unload thecheckingdata in oneof twoways. Onemethod is toclick on the
Checkingradiobutton in theLoad data portion of theGUI and then click on
Clear Data tounload thecheckingdata. Theother method you can useis to
closetheGUI and gotothecommand lineand retypeanfisedit. I n this case
you will havetoreloadthetrainingdata. After clearingthedata, you will need
toregenerateyour FI S. OncetheFI S is generated you can useyour first
trainingexperiencetodecideon thenumber of trainingepochs you want for
thesecond round of training.
ANFIS Editor GUI Example 2: Checking Data Doesnt
Validate Model
I n this example, weexaminewhat happens when thetrainingand checking
data sets aresufficiently different. WeseehowtheANFI S Editor GUI can be
used tolearn somethingabout data sets and howthey differ.
1 Clear both thetrainingand checkingdata.
2 YoucanpresstheClear Plot buttonontheright, althoughyoudont haveto.
3 Load fuzex2trnData and fuzex2chkData (respectively, thetrainingdata
and checkingdata) fromtheMATLAB workspacejust as you did in the
previous example.
anfis and the ANFIS Editor GUI
2-107
You should get somethingthat looks likethis:
+++ Checking data
ooo Training data
2 Tutorial
2-108
TraintheFI S for thissystemexactlyasyoudidinthepreviousexample, except
nowchoose60 Epochs beforetraining. You should get thefollowing:
Noticethecheckingerror is quitelarge. I t appears that theminimumchecking
error occurs within thefirst epoch. Recall that usingthecheckingdata option
with anfis automatically sets theFI S parameters tobethoseassociated with
theminimumcheckingerror. Clearly this set of membership functions would
not bethebest choicefor modelingthetrainingdata.
Whats wronghere? This exampleillustrates theproblemdiscussed earlier
wherein thecheckingdata set presented toanfis for trainingwas sufficiently
different fromthetrainingdataset. Asaresult, thetrainedFI S didnot capture
thefeatures of this data set very well. This illustrates theimportanceof
knowingthefeatures of your data set well enough when you select your
trainingand checkingdata. When this is not thecase, you can analyzethe
checkingerror plots toseewhether or not thecheckingdata performed
sufficiently well with thetrained model. I n this example, thecheckingerror is
sufficiently largetoindicatethat either moredata needs tobeselected for
training, or you may want tomodify your membership function choices (both
thenumber of membership functions and thetype). Otherwisethesystemcan
***
Training error
... Checking error
anfis and the ANFIS Editor GUI
2-109
beretrainedwithout thecheckingdata, if you think thetrainingdatacaptures
sufficiently thefeatures you aretryingtorepresent.
Tocompletethisexample, letstest thetrainedFI S model against thechecking
data. Todoso, click on Checkingdatain theTest FISportion of theGUI , and
click on Test Now. Thefollowingplot in theGUI indicates that thereis quitea
discrepancy between thecheckingdata output and theFI S output.
anfis from the Command Line
As you can see, generatingan FI S usingtheANFI S Editor GUI is quitesimple.
However, as you sawin thelast example, you need tobecautious about
implementingthecheckingdata validation featureof anfis. You must check
that thecheckingdata error does what is supposed to. Otherwiseyou need to
retrain theFI S.
I nthissectionwedescribehowtocarryout thecommandlinefeaturesof anfis
on a chaotic times-series prediction example.
2 Tutorial
2-110
Using anfis for Chaotic Time Series Prediction
Thedemomgtsdemo uses anfis topredict atimeseries that is generatedbythe
followingMackey-Glass (MG) time-delay differential equation:
This timeseries is chaotic, andsothereis noclearly defined period. Theseries
will not convergeor diverge, and thetrajectory is highly sensitivetoinitial
conditions. This is a benchmark problemin theneural network and fuzzy
modelingresearch communities.
Toobtain thetimeseries valueat integer points, weapplied thefourth-order
Runge-Kuttamethodtofindthenumerical solution totheaboveMG equation;
theresult was saved in thefilemgdata.dat. Hereweassumex(0) =1.2, =17,
and x(t) =0 for t <0. Toplot theMG timeseries, type
load mgdata.dat
t = mgdata(:, 1); x = mgdata(:, 2); plot(t, x);
I n time-series prediction wewant touseknown values of thetimeseries up to
thepoint in time, say, t, topredict thevalueat somepoint in thefuture, say,
t+P. Thestandard method for this typeof prediction is tocreatea mapping
x

t ( )
0.2x t ( )
1 x
10
t ( ) +
---------------------------------- 0.1x t ( ) =
anfis and the ANFIS Editor GUI
2-111
fromDsampledatapoints, sampledevery unitsintime, (x(t-(D-1)),..., x(t-),
x(t)), toapredictedfuturevaluex(t+P). Followingtheconventional settingsfor
predictingtheMG timeseries, weset D =4and =P =6. For each t, theinput
trainingdata for anfis is a four dimensional vector of thefollowingform:
w(t) = [x(t18) x(t12) x(t6) x(t)]
Theoutput trainingdata corresponds tothetrajectory prediction:
s(t) = x(t+6)
For each t, rangingin values from118to1117, thetraininginput/output data
will beastructurewhosefirst component is thefour-dimensional input w, and
whosesecond component is theoutput s. Therewill be1000input/output data
values. Weusethefirst 500 data values for theanfis training(thesebecome
thetrainingdataset), whiletheothers areusedascheckingdatafor validating
theidentified fuzzy model. This results in two500-point data structures:
trnData and chkData.
Hereis thecodethat 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, :);
Tostart thetraining, weneedan FI S structurethat specifiesthestructureand
initial parameters of theFI S for learning. This is thetask of genfis1:
fismat = genfis1(trnData);
Sincewedid not specify numbers and types of membership functions used in
theFI S, default values areassumed. Thesedefaults providetwogeneralized
bell membership functions on each of thefour inputs, eight altogether. The
generatedFI S structurecontains 16fuzzy rules with 104parameters. I n order
toachievegoodgeneralization capability, it is important tohavethenumber of
trainingdatapointsbeseveral timeslarger thanthenumber parametersbeing
estimated. I n this case, theratiobetween data and parameters is about five
(500/104).
2 Tutorial
2-112
Thefunction genfis1 generates initial membership functions that areequally
spaced and cover thewholeinput space. You can plot theinput membership
functions usingthefollowingcommands.
subplot(2,2,1)
plotmf(fismat, 'input', 1)
subplot(2,2,2)
plotmf(fismat, 'input', 2)
subplot(2,2,3)
plotmf(fismat, 'input', 3)
subplot(2,2,4)
plotmf(fismat, 'input', 4)
Theseinitial membership functions areshown below.
Tostart thetraining, type
[fismat1,error1,ss,fismat2,error2] = ...
anfis(trnData,fismat,[],[],chkData);
This takes about four minutes on a Sun SPARCstation 2 for 10 epochs of
training. Becausethecheckingdataoption of anfis was invoked, thefinal FI S
you choosewouldordinarily betheoneassociatedwith theminimumchecking
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 1
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 2
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 3
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 4
anfis and the ANFIS Editor GUI
2-113
error. This is stored in fismat2. Thefollowingcodewill plot thesenew
membership functions:
subplot(2,2,1)
plotmf(fismat2, 'input', 1)
subplot(2,2,2)
plotmf(fismat2, 'input', 2)
subplot(2,2,3)
plotmf(fismat2, 'input', 3)
subplot(2,2,4)
plotmf(fismat2, 'input', 4)
Hereis theresult:.
Toplot theerror signals type
plot([error1; error2]);
Hereerror1 and error2 aretheroot mean squared error for thetrainingand
checkingdata, respectively.
I n addition totheseerror plots, you maywant toplot theFI S output versus the
trainingor checkingdata. Tocomparetheoriginal MG timeseries and the
fuzzy prediction sideby side, try
anfis_output = evalfis([trnData; chkData], fismat2);
index = 125:1124;
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 1
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 2
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 3
0.6 0.8 1 1.2
0
0.2
0.4
0.6
0.8
1
Input 4
2 Tutorial
2-114
subplot(211), plot(t(index), [x(index) anfis_output]);
subplot(212), plot(t(index), x(index) anfis_output);
Notethat thedifferencebetween theoriginal MG timeseries and theanfis
estimated values is very small. This is why you can only seeonecurvein the
first plot. Theprediction error is shown in thesecond plot with a much finer
scale. Notethat wehaveonly trained for 10 epochs. Better performanceis
expected if weapply moreextensivetraining.
More on anfis and the ANFIS Editor GUI
Thecommand anfis takes at least twoand at most six input arguments. The
general format is
[fismat1,trnError,ss,fismat2,chkError] = ...
anfis(trnData,fismat,trnOpt,dispOpt,chkData,method);
wheretrnOpt (trainingoptions), dispOpt (display options), chkData (checking
data), and method (trainingmethod), areoptional. All of theoutput arguments
arealsooptional. I n this section wediscuss thearguments and range
components of thecommand linefunction anfis, as well as theanalogous
functionality of theANFI S Editor GUI .
When theANFI S Editor GUI is invoked usinganfisedit, only thetraining
dataset must exist prior toimplementinganfis.In addition, thestep-sizewill
be fixed when theadaptiveneuro-fuzzy systemis trained usingthis GUI tool.
200 300 400 500 600 700 800 900 1000 1100
10
5
0
5
x 10
3
Prediction Errors
200 300 400 500 600 700 800 900 1000 1100
0.6
0.8
1
1.2
MG Time Serise and ANFIS Prediction
anfis and the ANFIS Editor GUI
2-115
Training Data
Thetrainingdata, trnData, is a required argument toanfis, as well as tothe
ANFI S Editor GUI . Each rowof trnData is a desired input/output pair of the
target systemtobemodeled. Each rowstarts with an input vector and is
followedby an output value. Therefore, thenumber of rows of trnData is equal
tothenumber of trainingdata pairs, and, sincethereis only oneoutput, the
number of columns of trnData is equal tothenumber of inputs plus one.
Input FIS Structure
Theinput FI S structure, fismat, can beobtained either fromany of thefuzzy
editors: theFI S Editor, theMembership Function Editor, and theRuleEditor
fromtheANFI S Editor GUI , (which allows an FI S structuretobeloaded from
thedisk or theworkspace), or fromthecommand linefunction, genfis1 (for
which you only needtogivenumbers andtypes of membershipfunctions). The
FI S structurecontainsboth themodel structure, (which specifies suchitemsas
thenumber of rules in theFI S, thenumber of membership functions for each
input, etc.), and theparameters, (which specify theshapes of membership
functions). Therearetwomethods that anfis learningemploys for updating
membership function parameters: backpropagation for all parameters (a
steepest descent method), and a hybrid method consistingof backpropagation
for theparameters associated with theinput membership functions, and least
squares estimation for theparameters associatedwith theoutput membership
functions. As aresult, thetrainingerror decreases, at least locally, throughout
thelearningprocess. Therefore, themoretheinitial membership functions
resembletheoptimal ones, theeasier it will befor themodel parameter
trainingtoconverge. Human expertiseabout thetarget systemtobemodeled
may aidin settinguptheseinitial membershipfunction parameters in theFI S
structure.
Notethat genfis1 produces an FI S structurebased on a fixed number of
membership functions. This invokes theso-called curseof dimensionality, and
causes an explosion of thenumber of rules when thenumber of inputs is
moderatelylarge, that is, morethanfour or five. TheFuzzyLogicToolboxoffers
amethodthat will providefor somedimension reduction in thefuzzyinference
system: you can generatean FI S structureusingtheclusteringalgorithm
discussed in SubtractiveClustering on page2-123. FromtheANFI S Editor
GUI , this algorithmis selectedwith aradiobutton beforetheFI S is generated.
This subtractiveclusteringmethod partitions thedata intogroups called
clusters, and generates an FI S with theminimumnumber rules required to
distinguish thefuzzy qualities associated with each of theclusters.
2 Tutorial
2-116
Training Options
TheANFI S Editor GUI tool allows you tochooseyour desired error tolerance
and number of trainingepochs.
Trainingoption trnOpt for thecommand lineanfis is a vector that specifies
thestoppingcriteria and thestep-sizeadaptation strategy:
trnOpt(1): number of trainingepochs, default =10.
trnOpt(2): error tolerance, default =0.
trnOpt(3): initial step-size, default=0.01.
trnOpt(4): step-sizedecreaserate, default =0.9.
trnOpt(5): step-sizeincreaserate, default =1.1.
I f any element of trnOpt is an NaN or missing, then thedefault valueis taken.
Thetrainingprocess stops if thedesignated epoch number is reached or the
error goal is achieved, whichever comes first.
Usually wewant thestep-sizeprofiletobea curvethat increases initially,
reaches somemaximum, andthen decreases for theremainder of thetraining.
This ideal step-sizeprofileis achievedbyadjustingtheinitial step-sizeandthe
increaseand decreaserates (trnOpt(3) - trnOpt(5)). Thedefault values are
set uptocover awiderangeof learningtasks. For any specificapplication, you
may want tomodify thesestep-sizeoptions in order tooptimizethetraining.
However, as wementioned previously, therearenouser-specified step-size
options for trainingtheadaptiveneurofuzzyinferencesystemgeneratedusing
theANFI S Editor GUI .
Display Options
Display options only apply tothecommand linefunction, anfis.
For thecommandlineanfis, thedisplayoptionsargument, dispOpt, isavector
of either ones or zeros that specifies what information todisplay, (print in the
MATLAB command linewindow), before, during, and after thetraining
process. Oneis used todenoteprint this option, whereas zerodenotes dont
print this option.
dispOpt(1): display ANFI S 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.
anfis and the ANFIS Editor GUI
2-117
Thedefault modeis displays all availableinformation. I f any element of
dispOpt is NaN or missing, thedefault valuewill betaken.
Method
Both theANFI S Editor GUI and thecommand lineanfis apply either a
backpropagation formof thesteepest descent methodfor membershipfunction
parameter estimation, or a combination of backpropagation and the
least-squares method toestimatemembership function parameters. The
choices for this argument arehybrid or backpropagation. Thesemethod
choices aredesignated in thecommand linefunction, anfis, by 1 and 0,
respectively.
Output FIS Structure for Training Data
fismat1 is theoutput FI S structurecorrespondingtoaminimal trainingerror.
This is theFI S structurethat you will usetorepresent thefuzzy systemwhen
thereis nocheckingdata used for model crossvalidation. This data also
represents theFI S structurethat is savedby theANFI S Editor GUI when the
checkingdata option is not used.
Whenthecheckingdataoptionisused, theoutput savedisthat associatedwith
theminimumcheckingerror.
Training Error
Thetrainingerror is thedifferencebetween thetrainingdata output value,
and theoutput of thefuzzy inferencesystemcorrespondingtothesame
trainingdata input value, (theoneassociated with that trainingdata output
value). Thetrainingerror trnError records theroot mean squared error
(RMSE) of thetrainingdata set at each epoch. fismat1 is thesnapshot of the
FI S structurewhen thetrainingerror measureis at its minimum. TheANFI S
Editor GUI will plot thetrainingerror vs. epochs curveas thesystemis
trained.
Step-size
You cannot control thestep-sizeoptionswiththeANFI S Editor GUI . Usingthe
command lineanfis, thestep-sizearray ss records thestep-sizeduringthe
training. Plottingss gives thestep-sizeprofile, which serves as a referencefor
adjustingtheinitial step-sizeand thecorrespondingdecreaseand increase
2 Tutorial
2-118
rates. Thestep-size(ss) for thecommand linefunction anfis is updated
accordingtothefollowingguidelines:
I f theerror undergoes four consecutivereductions, increasethestep-sizeby
multiplyingit by a constant (ssinc) greater than one.
I f theerror undergoes twoconsecutivecombinations of oneincreaseandone
reduction, decreasethestep-sizeby multiplyingit by aconstant (ssdec) less
than one.
Thedefault valuefor theinitial step-sizeis 0.01; thedefault values for ssinc
and ssdec are1.1 and 0.9, respectively. All thedefault values can bechanged
via thetrainingoption for thecommand lineanfis.
Checking Data
Thecheckingdata, chkData, is usedfor testingthegeneralization capability of
thefuzzy inferencesystemat each epoch. Thecheckingdata has thesame
format asthat of thetrainingdata, anditselementsaregenerallydistinct from
thoseof thetrainingdata.
Thecheckingdata is important for learningtasks for which theinput number
is large, and/or thedata itself is noisy. I n general wewant a fuzzy inference
systemtotrack a given input/output data set well. Sincethemodel structure
usedfor anfis is fixed, thereis a tendency for themodel tooverfit thedata on
which is it trained, especially for a largenumber of trainingepochs. I f
overfittingdoes occur, wecannot expect thefuzzy inferencesystemtorespond
well toother independent datasets, especially if theyarecorruptedbynoise. A
validation or checkingdataset can beuseful for thesesituations. This dataset
is used tocrossvalidatethefuzzy inferencemodel. This crossvalidation is
accomplishedby applyingthecheckingdatatothemodel, andseeinghowwell
themodel responds tothis data.
When thecheckingdata option is used with anfis, either via thecommand
line, or usingtheANFI S Editor GUI , thecheckingdatais appliedtothemodel
at each trainingepoch. When thecommand lineanfis is invoked, themodel
parameters that correspond totheminimumcheckingerror arereturned via
theoutput argument fismat2. TheFI S membership function parameters
computed usingtheANFI S Editor GUI when both trainingand checkingdata
areloadedareassociatedwiththetrainingepochthat hasaminimumchecking
error.
anfis and the ANFIS Editor GUI
2-119
Theuseof theminimumcheckingdata error epoch toset themembership
function parameters assumes
Thecheckingdata is similar enough tothetrainingdata that thechecking
data error will decreaseas thetrainingbegins
Thecheckingdata increases at somepoint in thetraining, after which data
overfittinghas occurred.
As discussed in ANFI S Editor GUI Example2: CheckingData Doesnt
ValidateModelon page2-106, dependingon thebehavior of thecheckingdata
error, theresultingFI S may or may not betheoneyou should beusing.
Output FIS Structure for Checking Data
Theoutput of thecommand lineanfis, fismat2, is theoutput FI S structure
with theminimumcheckingerror. This is theFI S structurethat should be
used for further calculation if checkingdata is used for cross validation.
Checking Error
Thecheckingerror is thedifferencebetween thecheckingdata output value,
and theoutput of thefuzzy inferencesystemcorrespondingtothesame
checkingdata input value, (theoneassociated with that checkingdata output
value). Thecheckingerror chkError records theRMSE for thecheckingdata
at each epoch. fismat2 is thesnapshot of theFI S structurewhen thechecking
error is at its minimum. TheANFI S Editor GUI will plot thecheckingerror vs.
epochs curveas thesystemis trained.
2 Tutorial
2-120
Fuzzy Clustering
Clusteringof numerical dataformsthebasisof manyclassification andsystem
modelingalgorithms. Thepurposeof clusteringistoidentifynatural groupings
of data froma largedata set toproducea conciserepresentation of a systems
behavior. TheFuzzy LogicToolbox is equipped with sometools that allowyou
tofind clusters in input-output trainingdata. You can usethecluster
informationtogenerateaSugeno-typefuzzyinferencesystemthat best models
thedata behavior usinga minimumnumber of rules. Therules partition
themselves accordingtothefuzzy qualities associated with each of thedata
clusters. This typeof FI S generation can beaccomplished automatically using
thecommand linefunction, genfis2.
Fuzzy C-Means Clustering
Fuzzy c-means (FCM) is a data clusteringtechniquewherein each data point
belongs toa cluster tosomedegreethat is specified by a membership grade.
This techniquewas originally introducedby J imBezdek in 1981[Bez81] as an
improvement on earlier clusteringmethods. I t provides a method of howto
group data points that populatesomemultidimensional spaceintoa specific
number of different clusters?
TheFuzzy Logic Toolbox command linefunction fcm starts with an initial
guess for the cluster centers, which areintendedtomark themean location of
each cluster. Theinitial guess for thesecluster centers is most likely incorrect.
Additionally, fcm assigns every data point a membership gradefor each
cluster. Byiterativelyupdatingthecluster centersandthemembershipgrades
for each data point, fcm iteratively moves thecluster centers totheright
location within a data set. This iteration is based on minimizingan objective
function that represents thedistancefromany given data point toa cluster
center weighted by that data points membership grade.
fcm is a command linefunction whoseoutput is a list of cluster centers and
several membership grades for each data point. You can usetheinformation
returned by fcm tohelp you build a fuzzy inferencesystemby creating
membership functions torepresent thefuzzy qualities of each cluster.
Fuzzy Clustering
2-121
An Example: 2-D Clusters
Lets usesomequasi-randomtwo-dimensional data toillustratehowFCM
clusteringworks. Load a data set and takea look at it.
load fcmdata.dat
plot(fcmdata(:,1),fcmdata(:,2),'o')
Nowweinvokethecommandlinefunction, fcm, andask it tofindtwoclusters
in this data set
[center,U,objFcn] = fcm(fcmdata,2);
Iteration count = 1, obj. fcn = 8.941176
Iteration count = 2, obj. fcn = 7.277177
and soon until theobjectivefunction is nolonger decreasingmuch at all.
Thevariablecenter contains thecoordinates of thetwocluster centers, U
contains themembership grades for each of thedata points, and objFcn
contains a history of theobjectivefunction across theiterations.
Thefcm function is an iteration loop built on top of several other routines,
namely initfcm, which initializes theproblem, distfcm, which is used for
distancecalculations, and stepfcm, which steps through oneiteration.
0 0.2 0.4 0.6 0.8 1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1

.
2 Tutorial
2-122
Plottingtheobjectivefunction shows theprogress of theclustering.
plot(objFcn)
Finally hereis a plot displayingthetwoseparateclusters as classified by the
fcm routine. Thefollowingfigureis generated using:
load fcmdata.dat
[center, U, obj_fcn] = fcm(fcmdata, 2);
maxU = max(U);
index1 = find(U(1, :) == maxU);
index2 = find(U(2, :) == maxU);
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)
1 2 3 4 5 6 7 8 9 10 11
0
1
2
3
4
5
6
7
8
9
10
objective function values
Fuzzy Clustering
2-123
Cluster centers areindicated in thefigurebelowby thelargecharacters.
Subtractive Clustering
Supposewedont havea clear idea howmany clusters thereshould befor a
given set of data. Subtractiveclustering, [Chi94], is a fast, one-pass algorithm
for estimatingthenumber of clusters and thecluster centers in a set of data.
Thecluster estimates obtained fromthesubclust function can beused to
initializeiterativeoptimization-based clusteringmethods (fcm) and model
identificationmethods(likeanfis). Thesubclust functionfindstheclustersby
usingthesubtractiveclusteringmethod.
Thegenfis2 function builds upon thesubclust function toprovidea fast,
one-pass method totakeinput-output trainingdata and generatea
Sugeno-typefuzzy inferencesystemthat models thedata behavior.
An Example: Suburban Commuting
I n this exampleweapply thegenfis2 function tomodel therelationship
between thenumber of automobiletrips generatedfroman areaandtheareas
demographics. Demographic and trip data arefrom100 traffic analysis zones
in NewCastleCounty, Delaware. Fivedemographic factors areconsidered:
population, number of dwellingunits, vehicleownership, median household
income, and total employment. Hencethemodel has fiveinput variables and
oneoutput variable.
0 0.2 0.4 0.6 0.8 1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
2 Tutorial
2-124
Load thedata by typing
tripdata
subplot(2,1,1), plot(datin)
subplot(2,1,2), plot(datout)
tripdata creates several variables in theworkspace. Of theoriginal 100data
points, wewill use75 data points as trainingdata (datin and datout) and 25
data points as checkingdata, (as well as for test data tovalidatethemodel).
Thecheckingdatainput/output pairs aredenotedby chkdatin andchkdatout.
Thegenfis2 function generates a model fromdata usingclustering, and
requires you tospecify a cluster radius. Thecluster radius indicates therange
of influenceof a cluster when you consider thedata spaceas a unit hypercube.
Specifyinga small cluster radius will usually yield many small clusters in the
data, (resultingin many rules). Specifyinga largecluster radius will usually
yield a fewlargeclusters in thedata, (resultingin fewer rules). Thecluster
radius is specifiedas thethird argument of genfis2. Herewecall thegenfis2
function usinga cluster radius of 0.5.
fismat=genfis2(datin,datout,0.5);
genfis2 is a fast, one-pass method that does not performany iterative
optimization. An FI S structureis returned; themodel typefor theFI S
structureis afirst order Sugenomodel with threerules. Wecan useevalfis to
verify themodel.
fuzout=evalfis(datin,fismat);
trnRMSE=norm(fuzoutdatout)/sqrt(length(fuzout))
0 10 20 30 40 50 60 70 80
0
10
20
30
40
50
0 10 20 30 40 50 60 70 80
0
2
4
6
8
10
Fuzzy Clustering
2-125
trnRMSE =
0.5276
Thevariable trnRMSE is theroot mean squareerror of thesystemgeneratedby
thetrainingdata. Tovalidatethegeneralizability of themodel, weapply test
data totheFI S. For this example, weusethecheckingdata for both checking
and testingtheFI S parameters.
chkfuzout=evalfis(chkdatin,fismat);
chkRMSE=norm(chkfuzoutchkdatout)/sqrt(length(chkfuzout))
chkRMSE =
0.6170
Not surprisingly, themodel doesnt doquiteas good a job on thetestingdata.
A plot of thetestingdata reveals thedifference.
plot(chkdatout)
hold on
plot(chkfuzout,'o')
hold off
At this point, wecan usetheoptimization capability of anfis toimprovethe
model. First, wewill try usinga relatively short anfis training(50 epochs)
without implementingthecheckingdata option, but test theresultingFI S
model against thetest data. Thecommand lineversion of this is as follows:
fismat2=anfis([datin datout],fismat,[50 0 0.1]);
After thetrainingis done, wetype:
0 5 10 15 20 25
0
1
2
3
4
5
6
7
8
9
2 Tutorial
2-126
fuzout2=evalfis(datin,fismat2);
trnRMSE2=norm(fuzout2datout)/sqrt(length(fuzout2))
trnRMSE2 =
0.3407
chkfuzout2=evalfis(chkdatin,fismat2);
chkRMSE2=norm(chkfuzout2chkdatout)/sqrt(length(chkfuzout2))
chkRMSE2 =
0.5827
Themodel has improvedalot with respect tothetrainingdata, but onlyalittle
with respect tothecheckingdata. Hereis a plot of theimproved testingdata.
plot(chkdatout)
hold on
plot(chkfuzout2,'o')
hold off
Hereweseethat genfis2 can beused as a stand-alone, fast method for
generatinga fuzzy model fromdata, or as a pre-processor toanfis for
determiningtheinitial rules. An important advantageof usinga clustering
method tofind rules is that theresultant rules aremoretailored totheinput
data than they arein an FI S generated without clustering. This reduces the
problemof combinatorial explosion of rules when theinput data has a high
dimension (thedreaded curseof dimensionality).
Overfitting
Nowlets consider what happens if wecarry out a longer (200 epoch) training
of this systemusinganfis, includingits checkingdata option.
0 5 10 15 20 25
0
1
2
3
4
5
6
7
8
9
Fuzzy Clustering
2-127
[fismat3,trnErr,stepSize,fismat4,chkErr]= ...
anfis([datin datout],fismat2,[200 0
0.1],[], ...
[chkdatin chkdatout]);
Thelonglist of output argumentsreturnsahistoryof thestep-sizes, theRMSE
versus thetrainingdata, and theRMSE versus thecheckingdata associated
with each trainingepoch.
ANFIS training completed at epoch 200.
Minimal training RMSE = 0.326566
Minimal checking RMSE = 0.582545
This looks good. Theerror with thetrainingdata is thelowest weveseen, and
theerror with thecheckingdatais alsolower than before, though not by much.
This suggests that maybewehad gotten about as closeas possiblewith this
systemalready. Maybewehaveeven gonesofar as tooverfit thesystemtothe
trainingdata. Overfittingoccurs when wefit thefuzzy systemtothetraining
data sowell that it nolonger does a very good job of fittingthecheckingdata.
Theresult is a loss of generality. A look at theerror history against both the
trainingdata and thecheckingdata reveals much.
Herewecan seethat thetrainingerror settles at about the50
th
epoch point. I n
fact, thesmallest valueof thecheckingdata error occurs at epoch 52, after
which it increases slightly, even as anfis continues tominimizetheerror
against thetrainingdata all theway toepoch 200. Dependingon thespecified
Checking Error
Training Error
0 20 40 60 80 100 120 140 160 180 200
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
Epochs
2 Tutorial
2-128
error tolerance, thisplot alsoindicatesthemodels abilitytogeneralizethetest
data.
A Clustering GUI Tool
Thereis alsotheClusteringGUI , which implements fcm and subclust, along
with all of their options. I ts useis fairly self-evident.
TheclusteringGUI looks likethis, and is invoked usingthecommand line
function, findcluster.
You can invokefindcluster with a data set directly, in order toopen theGUI
with a data set. Thedata set must havetheextension .dat. For example, to
load thedata set, clusterdemo.dat, typefindcluster('clusterdemo.dat').
You usethepull-down tab under Method tochangebetween fcm(fuzzy
c-means) and subtractiv (subtractiveclustering). Moreinformation on the
options can befoundin theentries for fcm on page3-22, andsubclust on page
3-72, respectively.
Load a data set (*.dat)
Start clustering
Options change
with method
Choose fcm
clustering method.
into your directory.
the data.
Choose two of your data
variables to be plotted on
the screen. Once the data
is loaded, select them
with the pull-down tabs.
or subtractive
Save the value of
the cluster center.
Fuzzy Clustering
2-129
TheClusteringGUI works on multidimensional data sets, but only displays
twoof thosedimensions. Usethepull-down tabs under X-axis and Y-axis to
select which data dimension you want toview.
2 Tutorial
2-130
Stand-Alone C-Code Fuzzy Inference Engine
I n thefuzzy/fuzzy directoryof thetoolbox, you canfindtwoC files, fismain.c
and fis.c, which areprovided as thesourcecodes for a stand-alonefuzzy
inferenceengine. Thestand-aloneC-codefuzzy inferenceenginecan read an
FI S fileand an input data filetoperformfuzzy inferencedirectly, or it can be
embedded in other external applications.
Tocompilethestand-alonefuzzy inferenceengineon a UNI X system, type
% cc O o fismain fismain.c lm
(Notethat % is only symbolic of a UNI X prompt, and that you donot haveto
typefis.c explicitly, sinceit is included in fismain.c.) Upon successful
compilation, typetheexecutablecommand toseehowit works:
% fismain
This prompts thefollowingmessage:
% Usage: fismain data_file fis_file
This means that fismain needs twofiles todoits work: a data filecontaining
rows of input vectors, and an FI S filethat specifies thefuzzy inferencesystem
under consideration.
For example, consider an FI S structurefilenamed, mam21.fis. Wecan prepare
theinput data fileusingMATLAB:
[x, y] = meshgrid(5:5, 5:5);
input_data = [x(:) y(:)];
save fis_in input_data ascii
This saves all theinput data as a 121-by-2 matrix in theASCI I filefis_in,
whereeach rowof thematrix represents an input vector.
Nowwecan call thestand-alonecode:
% fismain fis_in mam21.fis
This generates 121 outputs on your screen. You can direct theoutputs to
another file:
% fismain fis_in mam21.fis > fis_out
Stand-Alone C-Code Fuzzy Inference Engine
2-131
Nowthefilefis_out contains a 121-by-1 matrix. I n general, each rowof the
output matrix represents an output vector. Thesyntax of fismain is similar to
its MEX-filecounterpart evalfis.m, except that all matrices arereplacedwith
files.
Tocomparetheresults fromtheMATLAB MEX-fileand thestand-alone
executable, typethefollowingwithin MATLAB:
fismat = readfis('mam21');
matlab_out = evalfis(input_data, fismat);
load fis_out
max(max(matlab_out fis_out))
ans =
4.9583e13
This tiny differencecomes fromthelimitedlength printout in thefilefis_out.
Thereareseveral things you should knowabout this stand-aloneexecutable:
I t is compatiblewith both ANSI and K & R standards for C code, as longas
__STDC__ is defined in ANSI compilers.
Customized functions arenot allowed in thestand-aloneexecutable, soyou
arelimited tothe11 membership functions that comewith thetoolbox, as
well as other factory settings for AND, OR, I MP, and AGG functions.
fismain.c contains only themain() function and it is heavily documented
for easy adaptation toother applications.
Toadd a newmembership function or newreasoningmechanismintothe
stand-alonecode, you need tochangethefilefis.c, which contains all the
necessary functions toperformthefuzzy inferenceprocess.
For theMacintosh, thecompiledcommandfismain tries tofindfismain.in
and fismain.fis as input data and FI S description files, respectively. The
output is stored in fismain.out. Thesefilenames aredefined within
Macintosh-specific #define symbols in fismain.c and can bechanged if
necessary.
2 Tutorial
2-132
Glossary
Thissectionisdesignedtobrieflyexplainsomeof thespecializedtermsthat are
derived fromfuzzy logic.
aggregation - thecombination of theconsequents of each rulein a Mamdani
fuzzy inferencesystemin preparation for defuzzification.
AdaptiveNeuro-Fuzzy InferenceSystem(ANFI S) - a techniquefor
automatically tuningSugeno-typeinferencesystems based on trainingdata.
antecedent - theinitial (or if) part of a fuzzy rule.
consequent - thefinal (or then) part of a fuzzy rule.
defuzzification - theprocess of transforminga fuzzy output of a fuzzy
inferencesystemintoa crisp output.
degreeof membership - theoutput of a membership function, this valueis
always limited tobetween 0 and 1. Alsoknown as a membership valueor
membership grade.
degreeof fulfillment - seefiringstrength.
firingstrength - thedegreetowhich theantecedent part of a fuzzy ruleis
satisfied. Thefiringstrength may betheresult of an AND or an OR operation,
and it shapes theoutput function for therule. Alsoknown as degreeof
fulfillment.
fuzzification - theprocess of generatingmembership values for a fuzzy
variableusingmembership functions.
fuzzy c-means clustering- a data clusteringtechniquewherein each data
point belongs toa cluster toa degreespecified by a membership grade.
fuzzy inferencesystem(FIS) - theoverall namefor a systemthat uses fuzzy
reasoningtomap an input spacetoan output space.
fuzzy operators - AND, OR, and NOT operators. Thesearealsoknown as
logical connectives.
fuzzy set - a set which can contain elements with only a partial degreeof
membership.
fuzzy singleton- afuzzyset with amembershipfunction that is unityat aone
particular point and zeroeverywhereelse.
Glossary
2-133
implication - theprocess of shapingthefuzzy set in theconsequent based on
theresults of theantecedent in a Mamdani-typeFI S.
Mamdani-typeinference- a typeof fuzzy inferencein which thefuzzy sets
fromtheconsequent of each rulearecombined through theaggregation
operator and theresultingfuzzy set is defuzzified toyield theoutput of the
system.
membership function (MF) - a function that specifies thedegreetowhich a
given input belongs toa set or is related toa concept.
singleton output function - an output function that is given by a spikeat a
singlenumber rather than acontinuous curve. I n theFuzzy LogicToolbox it is
only supported as part of a zero-order Sugenomodel.
subtractiveclustering- a techniquefor automatically generatingfuzzy
inferencesystems by detectingclusters in input-output trainingdata.
Sugeno-typeinference- a typeof fuzzy inferencein which theconsequent of
each ruleis alinear combination of theinputs. Theoutput is aweightedlinear
combination of theconsequents.
T-conorm- (alsoknown as S-norm) a two-input function that describes a
superset of fuzzy union (OR) operators, includingmaximum, algebraic sum,
and any of several parameterized T-conorms.
T-norm- a two-input function that describes a superset of fuzzy intersection
(AND) operators, includingminimum, algebraic product, and any of several
parameterized T-norms.
2 Tutorial
2-134
References
[Bez81] Bezdek, J .C., Pattern Recognition with Fuzzy ObjectiveFunction
Algorithms, PlenumPress, NewYork, 1981.
[Chi94] Chiu, S., Fuzzy Model I dentification Based on Cluster Estimation,
J ournal of I ntelligent & Fuzzy Systems, Vol. 2, No. 3, Sept. 1994.
[Dub80] Dubois, D. and H. Prade, Fuzzy Sets and Systems: Theory and
Applications, Academic Press, NewYork, 1980.
[J an91] J ang, J .-S. R., Fuzzy ModelingUsingGeneralized Neural Networks
and Kalman Filter Algorithm, Proc. of theNinth National Conf. on Artificial
I ntelligence(AAAI -91), pp. 762-767, J uly 1991.
[J an93] J ang, J .-S. R., ANFI S: Adaptive-Network-based Fuzzy I nference
Systems, I EEE Transactions on Systems, Man, and Cybernetics, Vol. 23, No.
3, pp. 665-685, May 1993.
[J an94] J ang, J .-S. R. and N. Gulley, Gain schedulingbased fuzzy controller
design,Proc. of theI nternational J oint Conferenceof theNorth American
Fuzzy I nformation ProcessingSociety Biannual Conference, theI ndustrial
Fuzzy Control and I ntelligent Systems Conference, and theNASA J oint
Technology Workshop on Neural Networks and Fuzzy Logic, San Antonio,
Texas, Dec. 1994.
[J an95] J ang, J .-S. R. and C.-T. Sun, Neuro-fuzzy modelingand control,
Proceedings of theI EEE, March 1995.
[J an97] J ang, J .-S. R. and C.-T. Sun, Neuro-Fuzzy and Soft Computing: A
Computational Approach toLearningand MachineI ntelligence, PrenticeHall,
1997.
[Kau85] Kaufmann, A. andM.M. Gupta, I ntroductiontoFuzzyArithmetic, V.N.
Reinhold, 1985.
[Lee90] Lee, C.-C., Fuzzy logicin control systems: fuzzy logiccontroller-parts
1and2,I EEE Transactions on Systems, Man, and Cybernetics, Vol. 20, No. 2,
pp 404-435, 1990.
[Mam75] Mamdani, E.H. and S. Assilian, An experiment in linguistic
synthesis with afuzzylogiccontroller,I nternational J ournal of Man-Machine
Studies, Vol. 7, No. 1, pp. 1-13, 1975.
References
2-135
[Mam76] Mamdani, E.H., Advances in thelinguistic synthesis of fuzzy
controllers,I nternational J ournal of Man-MachineStudies, Vol. 8, pp.
669-678, 1976.
[Mam77] Mamdani, E.H., Applicationsof fuzzylogictoapproximatereasoning
usinglinguistic synthesis,I EEE Transactions on Computers, Vol. 26, No. 12,
pp. 1182-1191, 1977.
[Sch63] Schweizer, B. and A. Sklar, Associativefunctions and abstract
semi-groups, Publ. Math Debrecen, 10:69-81, 1963.
[Sug77] Sugeno, M., Fuzzy measures and fuzzy integrals: a survey,(M.M.
Gupta, G. N. Saridis, and B.R. Gaines, editors) Fuzzy Automata and Decision
Processes, pp. 89-102, North-Holland, NewYork, 1977.
[Sug85] Sugeno, M., I ndustrial applications of fuzzy control, Elsevier Science
Pub. Co., 1985.
[Wan94] Wang, L.-X., Adaptivefuzzysystems and control: design and stability
analysis, PrenticeHall, 1994.
[WidS85] Widrow, B. and D. Stearns, AdaptiveSignal Processing, Prentice
Hall, 1985.
[Yag80] Yager, R., On a general class of fuzzy connectives, Fuzzy Sets and
Systems, 4:235-242, 1980.
[Yag94] Yager, R. and D. Filev, Generation of Fuzzy Rules by Mountain
Clustering,J ournal of I ntelligent & FuzzySystems, Vol. 2, No. 3, pp. 209-219,
1994.
[Zad65] Zadeh, L.A., Fuzzysets,I nformationandControl, Vol. 8, pp. 338-353,
1965.
[Zad73] Zadeh, L.A., Outlineof a newapproach totheanalysis of complex
systems and decision processes,I EEE Transactions on Systems, Man, and
Cybernetics, Vol. 3, No. 1, pp. 28-44, J an. 1973.
[Zad75] Zadeh, L.A., Theconcept of alinguisticvariableandits application to
approximatereasoning, Parts 1, 2, and 3,I nformation Sciences, 1975,
8:199-249, 8:301-357, 9:43-80
[Zad88] Zadeh, L.A., Fuzzy Logic,Computer, Vol. 1, No. 4, pp. 83-93, 1988.
[Zad89] Zadeh, L.A., Knowledgerepresentation in fuzzy logic, I EEE
Transactions on Knowledgeand Data Engineering, Vol. 1, pp. 89-100, 1989.
2 Tutorial
2-136
3
Reference
GUI Tools . . . . . . . . . . . . . . . . . . . . . . 3-2
Membership Functions . . . . . . . . . . . . . . . . 3-2
FI S Data StructureManagement . . . . . . . . . . . . 3-3
Advanced Techniques . . . . . . . . . . . . . . . . . 3-4
Simulink Blocks . . . . . . . . . . . . . . . . . . . 3-4
Demos . . . . . . . . . . . . . . . . . . . . . . . 3-5
3 Reference
3-2
This section of thechapter contains brief descriptions of all thefunctionsin the
Fuzzy LogicToolbox. Thefollowingtables contain thefunctions listed by topic.
GUI Tools
Membership Functions
Function Purpose
anfisedit ANFI S Editor GUI .
fuzzy Basic FI S Editor.
mfedit Membership Function Editor.
ruleedit RuleEditor and parser.
ruleview RuleViewer and fuzzy inferencediagram.
surfview Output SurfaceViewer.
Function Purpose
dsigmf Differenceof twosigmoid membership functions.
gauss2mf Two-sided Gaussian curvemembership function.
gaussmf Gaussian curvemembership function.
gbellmf Generalized bell curvemembership function.
pimf Pi-shaped curvemembership function.
3-3
FIS Data Structure Management
psigmf Product of twosigmoidal membership functions.
smf S-shaped curvemembership function.
sigmf Sigmoid curvemembership function.
trapmf Trapezoidal membership function.
trimf Triangular membership function.
zmf Z-shaped curvemembership function.
Function Purpose
addmf Add membership function toFI S.
addrule Add ruletoFI S.
addvar Add variabletoFI S.
defuzz Defuzzify membership function.
evalfis Performfuzzy inferencecalculation.
evalmf Generic membership function evaluation.
gensurf GenerateFI S output surface.
getfis Get fuzzy systemproperties.
mf2mf Translateparameters between functions.
newfis CreatenewFI S.
parsrule Parsefuzzy rules.
plotfis Display FI S input-output structure.
plotmf Plot all of themembership functions associated
with a given variable.
Function Purpose
3 Reference
3-4
Advanced Techniques
Simulink Blocks
readfis Load FI S fromdisk.
rmmf Removemembership function fromFI S.
rmvar RemovevariablefromFI S.
setfis Set fuzzy systemproperties.
showfis Display annotated FI S.
showrule Display FI S rules.
writefis SaveFI S todisk.
Function Purpose
anfis Trainingroutinefor a Sugeno-typeFI S (MEX only).
fcm Find clusters with FCM clustering.
genfis1 GenerateFI S matrix usinggrid method.
genfis2 GenerateFI S matrix usingsubtractiveclustering.
subclust Find cluster centers with subtractiveclustering.
Function Purpose
fuzblock Fuzzy logic controller blocks and demoblocks.
sffis Fuzzy inferenceS-function.
Function Purpose
3-5
Demos
Function Purpose
defuzzdm Defuzzification methods.
fcmdemo FCM clusteringdemo(2-D).
fuzdemos GUI for Fuzzy Logic Toolbox demos.
gasdemo ANFI S demofor fuel efficiency usingsubclustering.
juggler Ball-juggler with RuleViewer.
invkine I nversekinematics of a robot arm.
irisfcm FCM clusteringdemo(4-D).
noisedm Adaptivenoisecancellation.
slbb Ball and beamcontrol (Simulink ).
slcp I nverted pendulumcontrol (Simulink ).
sltank Water level control (Simulink).
sltankrule Water level control with RuleViewer (Simulink).
sltbu Truck backer-upper (Simulink only).
addmf
3-6
3addmf
Purpose Add a membership function toan FI S.
Synopsis a = addmf(a,'varType',varIndex,'mfName','mfType',mfParams)
Description A membershipfunctioncanonlybeaddedtoavariablein anexistingMATLAB
workspaceFI S. I ndices areassigned tomembership functions in theorder in
which theyareadded, sothefirst membershipfunction addedtoavariablewill
always beknown as membership function number onefor that variable. You
cannot adda membershipfunction toinput variablenumber twoof asystemif
only oneinput has been defined.
Thefunction requires six input arguments in this order:
1 A MATLAB variablenameof a FI S structurein theworkspace
2 A stringrepresentingthetypeof variableyou want toadd themembership
function to('input' or 'output')
3 Theindex of thevariableyou want toadd themembership function to
4 A stringrepresentingthenameof thenewmembership function
5 A stringrepresentingthetypeof thenewmembership function
6 Thevector of parameters that specify themembership function
addmf
3-7
Example 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)
See Also addrule, addvar, plotmf, rmmf, rmvar
0 1 2 3 4 5 6 7 8 9 10
0
0.2
0.4
0.6
0.8
1
service
D
e
g
r
e
e

o
f

b
e
l
i
e
f
poor good
excellent
addrule
3-8
3addrule
Purpose Add a ruletoan FI S.
Synopsis a = addrule(a,ruleList)
Description addrule has twoarguments. Thefirst argument is theMATLAB workspace
variableFI S name. Thesecondargument for addrule isamatrixof oneor more
rows, eachof whichrepresentsagivenrule. Theformat that therulelist matrix
must takeis veryspecific. I f therearem inputstoasystemandn outputs, there
must beexactly m +n +2 columns totherulelist.
Thefirst m columns refer totheinputs of thesystem. Each column contains a
number that refers totheindex of themembership function for that variable.
Thenext n columns refer totheoutputs of thesystem. Each column contains a
number that refers totheindex of themembership function for that variable.
Them +n +1 column contains theweight that is tobeapplied totherule. The
weight must bea number between zeroand one, and is generally left as one.
Them +n +2column contains a1if thefuzzy operator for therules antecedent
is AND. I t contains a 2 if thefuzzy operator is OR.
Example ruleList=[
1 1 1 1 1
1 2 2 1 1];
a = addrule(a,ruleList);
I f theabovesystema has twoinputs and oneoutput, thefirst rulecan be
interpreted as: I f input 1is MF 1and input 2is MF 1, then output 1is MF 1.
See Also addmf, addvar, rmmf, rmvar, parsrule, showrule
addvar
3-9
3addvar
Purpose Add a variabletoan FI S.
Synopsis a = addvar(a,'varType','varName',varBounds)
Description addvar has four arguments in this order:
1 Thenameof a FI S structurein theMATLAB workspace
2 A stringrepresentingthetypeof thevariableyou want toadd ('input' or
'output')
3 A stringrepresentingthenameof thevariableyou want toadd
4 Thevector describingthelimitingrangevalues for thevariableyou want to
add
I ndices areapplied tovariables in theorder in which they areadded, sothe
first input variableadded toa systemwill always beknown as input variable
number onefor that system. I nput and output variables arenumbered
independently.
Example a=newfis('tipper');
a=addvar(a,'input','service',[0 10]);
getfis(a,'input',1)
MATLAB replies
Name = service
NumMFs = 0
MFLabels =
Range = [0 10]
See Also addmf, addrule, rmmf, rmvar
anfis
3-10
3anfis
Purpose Trainingroutinefor Sugeno-typeFI S (MEX only).
Synopsis [fismat,error1,stepsize] = anfis(trnData)
[fismat,error1,stepsize] = anfis(trnData,fismat)
[fismat1,error1,stepsize] = ...
anfis(trnData,fismat,trnOpt,dispOpt)
[fismat1,error1,stepsize,fismat2,error2] = ...
anfis(trnData,trnOpt,dispOpt,chkData)
[fismat1,error1,stepsize,fismat2,error2] = ...
anfis(trnData,trnOpt,dispOpt,chkData,optMethod)
Description This is themajor trainingroutinefor Sugeno-typefuzzy inferencesystems.
anfis uses a hybrid learningalgorithmtoidentify parameters of Sugeno-type
fuzzy inferencesystems. I t applies a combination of theleast-squares method
and thebackpropagation gradient descent method for trainingFI S
membership function parameters toemulatea given trainingdata set. anfis
can alsobeinvokedusingan optional argument for model validation. Thetype
of model validation that takes placewith this option is a checkingfor model
overfitting, and theargument is a data set called thecheckingdata set.
Thearguments in theabovedescription for anfis areas follows:
trnData: thenameof a trainingdata set. This is a matrix with all but the
last column containinginput data, whilethelast column contains a single
vector of output data.
fismat: thenameof an FI S, (fuzzy inferencesystem) used toprovideanfis
with an initial set of membershipfunctions for training. Without this option,
anfis will usegenfis1 toimplement a default initial FI S for training. This
default FI S will havetwomembershipfunctions of theGaussian type, when
invokedwithonlyoneargument. I f fismat isprovidedasasinglenumber (or
a vector), it is taken as thenumber of membership functions (or thevector
whoseentries aretherespectivenumbers of membership functions
associated with each respectiveinput when thesenumbers differ for each
input). I n this case, both arguments of anfis arepassed togenfis1 to
generatea valid FI S structurebeforestartingthetrainingprocess.
anfis
3-11
trnOpt: vector of trainingoptions. When any trainingoption is entered as
NaN thedefault options will bein force. Theseoptions areas follows:
trnOpt(1): trainingepoch number (default: 10)
trnOpt(2): trainingerror goal (default: 0)
trnOpt(3): initial step size(default: 0.01)
trnOpt(4): step sizedecreaserate(default: 0.9)
trnOpt(5): step sizeincreaserate(default: 1.1)
dispOpt: vector of displayoptionsthat specifywhat messagetodisplayinthe
MATLAB command windowduringtraining. Thedefault valuefor any
display option is 1, which means thecorrespondinginformation is displayed.
A 0 means thecorrespondinginformation is not displayed on thescreen.
When any display option is entered as NaN, thedefault options will bein
force. Theseoptions areas follows:
dispOpt(1): ANFI S information, such as numbers of input and output
membership functions, and soon (default: 1)
dispOpt(2): error (default: 1)
dispOpt(3): step sizeat each parameter update(default: 1)
dispOpt(4): final results (default: 1)
chkData: thenameof an optional checkingdata set for overfittingmodel
validation. This data set is a matrix in thesameformat as thetrainingdata
set.
optMethod: optional optimization method used in membership function
parameter training: either 1 for thehybrid method or 0 for the
backpropagation method. Thedefault methodis thehybridmethod, which is
acombinationof least squaresestimationwithbackpropagation. Thedefault
method is invoked whenever theentry for this argument is anythingbut 0.
Thetrainingprocess stops whenever thedesignated epoch number is reached
or thetrainingerror goal is achieved.
anfis
3-12
Note on anfis arguments: When anfis is invoked with twoor more
arguments, any optional arguments will takeon their default values if they
areentered as NaNs or empty matrices. Default values can bechanged directly
by modifyingthefileanfis.m. Either NaNs or empty matrices must beused as
place-holders for variables if you dont want tospecify them, but dowant to
specify succeedingarguments, for example, when you implement thechecking
data option of anfis.
Therangevariables in theabovedescription for anfis areas follows:
fismat1 is theFI S structurewhoseparameters areset accordingtoa
minimumtrainingerror criterion.
error1 or error2 is an array of root mean squarederrors representingthe
trainingdata error signal and thecheckingdata error signal, respectively.
stepsize is an array of stepsizes. Thestepsizeis decreased(by multiplying
it with thecomponent of thetrainingoption correspondingtothestep size
decreaserate) if theerror measureundergoes twoconsecutivecombinations
of an increasefollowed by a decrease. Thestep sizeis increased (by
multiplyingit with theincreaserate) if theerror measureundergoes four
consecutivedecreases.
fismat2 is theFI S structurewhoseparameters areset accordingtoa
minimumcheckingerror criterion.
anfis
3-13
Example x = (0:0.1:10)';
y = sin(2*x)./exp(x/5);
trnData = [x y];
numMFs = 5;
mfType = 'gbellmf';
epoch_n = 20;
in_fismat = genfis1(trnData,numMFs,mfType);
out_fismat = anfis(trnData,in_fismat,20);
plot(x,y,x,evalfis(x,out_fismat));
legend('Training Data','ANFIS Output');
See Also genfis1, anfis
References J ang, J .-S. R., Fuzzy ModelingUsingGeneralized Neural Networks and
Kalman Filter Algorithm, Proc. of theNinth National Conf. on Artificial
I ntelligence(AAAI -91), pp. 762-767, J uly 1991.
J ang, J .-S. R., ANFI S: Adaptive-Network-based Fuzzy I nferenceSystems,
I EEE Transactions on Systems, Man, and Cybernetics, Vol. 23, No. 3, pp.
665-685, May 1993.
anfisedit
3-14
3anfisedit
Purpose Toopen theANFI S Editor GUI .
Synopsis anfisedit('a')
anfisedit(a)
anfisedit
Description
Usinganfisedit, you bringuptheANFI S Editor GUI fromwhich you can load
a data set and train anfis. TheANFI S Editor GUI invoked using
Test data against
the FIS model. The
plot appears in the
plot region.
Testing Data appears on the
plot in blue as
Training Data appears on
the plot in blue as
Checking Data appears on
the plot in blue as
FIS Output appears on the
screen in red as
...
o o o
+++
***
Load or save fuzzy
Sugeno system or open
new Sugeno system.
Undo
Open FIS or Edit with any
of the other GUIs.
Status of the number of inputs,
outputs, input membership functions
and output membership functions
Load either training,
testing, or checking
data from disk or
workspace, or load
demo data. Data
appears in the plot
region.
Clear Data unloads a loaded data
set checked under Type:.
The plot region is cleared even if other
data types are still loaded.
Load FIS or generate FIS
from loaded data using
your chosen number of MFs
and rules or fuzzy.
Train FIS after setting optimization
method, error tolerance, and number
of epochs. This generates error plots
in the plot region.
After you generate
or load a FIS, this
button allows you to
open a graphical
representation of its
input/output
structure.
Plot region
anfisedit
3-15
anfisedit('a'), brings up theANFI S Editor GUI fromwhich you can
implement anfis usinga FI S structurestored as a fileon your disk called,
a.fis.
anfisedit(a) operatesthesamewayfor aFI S structurea, storedasavariable
in theMATLAB workspace.
Refer toanfis and theANFI S Editor GUI on page2-92 for moreinformation
about howtouseanfisedit.
Menu Items On theANFI S Editor GUI , thereis a menu bar that allows you toopen related
GUI tools, open andsavesystems, andsoon. TheFilemenu is thesameas the
onefound on theFI S Editor. Refer tofuzzy on page3-29for moreinformation.
UsethefollowingEdit menu item:
Undo toundothemost recent change.
UsethefollowingViewmenu items:
Edit FIS properties... toinvoketheFI S Editor.
Edit rules... toinvoketheRuleEditor.
Edit membershipfunctions... toinvoketheMembershipFunctionEditor.
Viewrules... toinvoketheRuleViewer.
Viewsurface... toinvoketheSurfaceViewer.
See Also fuzzy, mfedit, ruleedit, ruleview, surfview
convertfis
3-16
3convertfis
Purpose Convert a Fuzzy Logic Toolbox version 1.0 FI S matrix toa version 2.0 FI S
structure.
Synopsis fis_new=convertfis(fis_old)
Description convertfis takes a version 1.0 FI S matrix and converts it toa version 2.0
structure.
defuzz
3-17
3defuzz
Purpose Defuzzify membership function.
Synopsis out = defuzz(x,mf,type)
Description defuzz(x,mf,type) returns adefuzzifiedvalueout, of amembershipfunction
mf positionedat associatedvariablevaluex, usingoneof several defuzzification
strategies, accordingtotheargument, type. Thevariabletype canbeoneof the
following.
centroid: centroid of area method
bisector: bisector of area method
mom: mean of maximummethod
som: smallest of maximummethod
lom: largest of maximummethod
I f type isnot oneof theabove, it isassumedtobeauser-definedfunction. x and
mf arepassed tothis function togeneratethedefuzzified output.
Examples x = 10:0.1:10;
mf = trapmf(x,[10 8 4 7]);
xx = defuzz(x,mf,'centroid');
dsigmf
3-18
3dsigmf
Purpose Built-in membership function composed of thedifferencebetween two
sigmoidal membership functions.
Synopsis y = dsigmf(x,[a1 c1 a2 c2])
Description Thesigmoidal membershipfunction usedheredepends on thetwoparameters
a and c and is given by
Themembership function dsigmf depends on four parameters, a1, c1, a2, and
c2, and is thedifferencebetween twoof thesesigmoidal functions:
f
1
(x; a1, c
1
) - f
2
(x; a2, c
2
)
Theparameters arelisted in theorder: [a1 c
1
a
2
c
2
].
Example x=0:0.1:10;
y=dsigmf(x,[5 2 5 7]);
plot(x,y)
xlabel('dsigmf, P=[5 2 5 7]')
See Also gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf, trapmf,
trimf, zmf
f x a ; c , ( )
1
1 e
a x c ( )
+
------------------------------- =
0 2 4 6 8 10
0
0.25
0.5
0.75
1
dsigmf, P = [5 2 5 7]
evalfis
3-19
3evalfis
Purpose Performfuzzy inferencecalculations.
Synopsis 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 evalfis has thefollowingarguments:
input: a number or a matrix specifyinginput values. I f input is an M-by-N
matrix, whereN is number of input variables, then evalfis takes each row
of input as an input vector and returns theM-by-L matrix tothevariable,
output, whereeach rowis an output vector and L is thenumber of output
variables.
fismat: an FI S structuretobeevaluated.
numPts: an optional argument that represents thenumber of samplepoints
on which toevaluatethemembership functions over theinput or output
range. I f this argument is not used, thedefault valueof 101 point is used.
Therangelabels for evalfis areas follows:
output: theoutput matrix of sizeM-by-L, whereM represents thenumber of
input values specifiedabove, andL is thenumber of output variables for the
FI S.
Theoptional rangevariables for evalfis areonly calculated when theinput
argument is a rowvector, (only oneset of inputs is applied). Theseoptional
rangevariables are:
IRR: theresult of evaluatingtheinput values through themembership
functions. This is a matrix of sizenumRules-by-N, wherenumRules is the
number of rules, and N is thenumber of input variables.
ORR: theresult of evaluatingtheoutput values through themembership
functions. This is a matrix of sizenumPts-by-numRules*L, wherenumRules
is thenumber of rules, and L is thenumber of outputs. Thefirst numRules
columns of this matrix correspond tothefirst output, thenext numRules
columns of this matrix correspond tothesecond output, and soforth.
ARR: thenumPts-by-L matrixof theaggregatevaluessampledat numPts along
theoutput rangefor each output.
evalfis
3-20
When invokedwith only onerangevariable, this function computes theoutput
vector, output, of thefuzzy inferencesystemspecified by thestructure,
fismat, for theinput valuespecified by thenumber or matrix, input.
Example fismat = readfis('tipper');
out = evalfis([2 1; 4 9],fismat)
This generates theresponse
out =
7.0169
19.6810
See Also ruleview, gensurf
evalmf
3-21
3evalmf
Purpose Generic membership function evaluation.
Synopsis y = evalmf(x,mfParams,mfType)
Description evalmf evaluates any membership function, wherex is thevariablerangefor
themembership function evaluation, mfType is a membership function from
thetoolbox, and mfParams areappropriateparameters for that function.
I f you want tocreateyour own custommembership function, evalmf will still
work, becauseit evaluates any membership function whosenameit doesnt
recognize.
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]')
See Also dsigmf, gaussmf, gauss2mf, gbellmf, mf2mf, pimf, psigmf, sigmf, smf, trapmf,
trimf, zmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
gbellmf, P = [2 4 6]
fcm
3-22
3fcm
Purpose Fuzzy c-means clustering.
Synopsis [center,U,obj_fcn] = fcm(data,cluster_n)
Description [center, U, obj_fcn] = fcm(data, cluster_n) applies thefuzzy c-means
clusteringmethod toa given data set.
Theinput arguments of this function are:
data: data set tobeclustered; each rowis a sampledata point
cluster_n: number of clusters (greater than one)
Theoutput arguments of this function are:
center: matrix of final cluster centers whereeach rowprovides thecenter
coordinates
U: final fuzzy partition matrix (or membership function matrix)
obj_fcn: values of theobjectivefunction duringiterations
fcm(data,cluster_n,options) uses an additional argument variable,
options, tocontrol clusteringparameters, introducea stoppingcriteria, and/
or set theiteration information display:
options(1): exponent for thepartition matrix U (default: 2.0)
options(2): maximumnumber of iterations (default: 100)
options(3): minimumamount of improvement (default: 1e-5)
options(4): infodisplay duringiteration (default: 1)
I f anyentryof options is NaN, thedefault valuefor that option is usedinstead.
Theclusteringprocess stops when themaximumnumber of iterations is
reached, or when theobjectivefunction improvement between twoconsecutive
iterations is less than theminimumamount of improvement specified.
fcm
3-23
Example data = rand(100, 2);
[center,U,obj_fcn] = fcm(data, 2);
plot(data(:,1), data(:,2),'o');
maxU = max(U);
index1 = find(U(1,:) == maxU);
index2 = find(U(2, :) == maxU);
line(data(index1,1), data(index1, 2), 'linestyle', 'none',
'marker', '*',
'color', 'g');
line(data(index2,1), data(index2, 2), 'linestyle', 'none',
'marker', '*',
'color', 'r');
findcluster
3-24
3findcluster
Purpose I nteractiveclusteringGUI for fuzzy c-means and subclustering.
Synopsis findcluster
findcluster('file.dat')
Description findcluster brings up a GUI toimplement fuzzy c-means (fcm) and/or fuzzy
subtractiveclustering(subtractiv) usingthepull-down tabunder Method on
theGUI . Data is entered usingtheLoad Data button. Theoptions for each of
thesemethods areset todefault values. Thesecan bechanged. A description of
theoptions for fuzzy c-means is foundin fcm on page3-22. A description of the
options for fuzzy subclusteringis found in subclust on page3-72.
This tool works on multidimensional data sets, but only displays twoof those
dimensions. Usethepull-down tabs under X-axis and Y-axis toselect which
data dimension you want toview. For example, if you havedata that is
five-dimensional, this tool labels thedata as data_1, data_2, data_3, data_4,
data_5, in theorder in which thedata appears in thedata set. Start will
performtheclustering, and SaveCenter will savethecluster center.
When operatingon a data set, file.dat, findcluster (file.dat) loads the
dataset automatically, plottinguptothefirst twodimensions of thedataonly.
findcluster
3-25
You can still choosewhich twodimensions of thedatayou want tocluster after
theGUI comes up.
Example findcluster('clusterdemo.dat')
See Also fcm, subclust
fuzarith
3-26
3fuzarith
Purpose Toperformfuzzy arithmetic.
Synopsis C = fuzarith(X, A, B, operator)
Description Usinginterval arithmetic, C = fuzarith(X, A, B, operator) returns afuzzy set
C as theresult of applyingthefunction represented by thestring, operator,
that performsabinaryoperationonthesampledconvexfuzzysetsA andB. The
elements of A andB arederivedfromconvex functions of thesampleduniverse,
X.
A, B, and X arevectors of thesamedimension.
operator is oneof thefollowingstrings: 'sum', 'sub', 'prod', and 'div'.
Thereturned fuzzy set C is a column vector with thesamelength as X.
Remark Fuzzy addition might generatethemessage: divideby zero, but this will not
affect thecorrectness of this function.
Example 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
3-27
3fuzblock
Purpose Simulink fuzzy logic controller block.
Synopsis fuzblock
Description Thiscommandbrings upaSimulink systemthat, inaddition tosomeSimulink
demoblocks, contains twoSimulink blocks you can use:
TheFuzzy Logic Controller
TheFuzzy Logic Controller With RuleViewer, (seealsoruleview on page
3-61). This block forces theRuleViewer topop open duringa Simulink
simulation.
Thedialogboxassociatedwitheither of theseblocksisfoundbydouble-clicking
on theFuzzy Logic Controller block. This box contains thenameof theFI S
structurein theworkspacethat corresponds tothedesired fuzzy systemyou
want in your Simulink model.
Toopen this dialogbox for theFuzzy LogicController With RuleViewer block,
you haveto
1 Double-click on this block, and a Simulink diagramwith a Fuzzy Logic
Controller block opens.
2 Double-click on thesecond Fuzzy Logic Controller block that pops open.
I f thefuzzy inferencesystemhas multipleinputs, theseinputs should be
multiplexed together beforefeedingthemintoeither theFuzzy Logic
Controller or theFuzzy Logic Controller With RuleViewer block. Similarly, if
thesystemhas multipleoutputs, thesesignals will bepassed out of theblock
on onemultiplexed line.
See Also sffis, ruleview
fuzdemos
3-28
3fuzdemos
Purpose List of all Fuzzy Logic Toolbox demos.
Synopsis fuzdemos
Description This function brings upaGUI that allows you tochoosebetween anyof several
Fuzzy Logic Toolbox demos listed under Demos on page3-5.
fuzzy
3-29
3fuzzy
Purpose Toinvokethebasic FI S editor.
Synopsis fuzzy
fuzzy(fismat)
ThisGUI tool allowsyoutoedit thehighest level featuresof thefuzzyinference
system, such as thenumber of input and output variables, thedefuzzification
methodused, andsoon. Refer toTheFI S Editoron page2-49andff., for more
information about howtousetheGUI s associated with fuzzy.
TheFI S Editor is thehigh-level display for any fuzzy logicinferencesystem. I t
allows you tocall thevariousother editors tooperateon theFI S. This interface
allows convenient access toall other editors with an emphasis on maximum
flexibility for interaction with thefuzzy system.
The Diagram Thediagramdisplayedat thetopof thewindowshows theinputs, outputs, and
a central fuzzy ruleprocessor. Click on oneof thevariableboxes tomakethe
selected box thecurrent variable. You should seethebox highlighted in red.
Double-click on oneof thevariables tobringup theMembership Function
Editor. Double-click on thefuzzy ruleprocessor tobringup theRuleEditor. I f
fuzzy
3-30
a variableexists but is not mentioned in therulebase, it is connected tothe
ruleprocessor block with a dashed rather than a solid line.
Menu Items TheFI S Editor displays a menu bar that allows you toopen relatedGUI tools,
open and savesystems, and soon.
Under Fileselect:
NewMamdani FIS... toopen a newMamdani-stylesystemwith no
variables and norules called Untitled.
NewSugeno FIS... toopen a newSugeno-stylesystemwith novariables
and norules called Untitled.
Open fromdisk... toload a systemfroma specified .fis fileon disk.
Saveto disk tosavethecurrent systemtoa .fis fileon disk.
Saveto disk as... tosavethecurrent systemtodisk with theoption to
renameor relocatethefile.
Open fromworkspace... toload a systemfroma specified FI S structure
variablein theworkspace.
Saveto workspace... tosavethesystemtothecurrently named FI S
structurevariablein theworkspace.
Saveto workspaceas... tosavethesystemtoa specified FI S structure
variablein theworkspace.
ClosewindowtoclosetheGUI .
Under Edit select:
Add input toadd another input tothecurrent system.
Add output toadd another output tothecurrent system.
Removevariabletodeletea selected variable.
Undo toundothemost recent change.
Under Viewselect:
Edit MFs... toinvoketheMembership Function Editor.
Edit rules... toinvoketheRuleEditor.
Edit anfis... toinvoketheANFI S Editor for singleoutput Sugenosystems
only.
Viewrules... toinvoketheRuleViewer.
Viewsurface... toinvoketheSurfaceViewer.
fuzzy
3-31
Inference
Method Pop-up
Menus
Fivepop-up menus areprovided tochangethefunctionality of thefivebasic
steps in thefuzzy implication process:
And method: Choosemin, prod, or Custom, for a customoperation.
Or method: Choosemax, probor (probabilistic or), or Custom, for a custom
operation.
Implication method: Choosemin, prod, or Custom, for a customoperation.
This selection is not availablefor Sugeno-stylefuzzy inference.
Aggregation method: Choosemax, sum, probor, or Custom, for a custom
operation. This selection is not availablefor Sugeno-stylefuzzy inference.
Defuzzification method: For Mamdani-styleinference, choosecentroid,
bisector, mom (middleof maximum), som (smallest of maximum), lom
(largest of maximum), or Custom, for a customoperation. For Sugeno-style
inference, choosebetween wtaver (weighted average) or wtsum (weighted
sum).
See Also mfedit, ruleedit, ruleview, surfview, anfisedit
gauss2mf
3-32
3gauss2mf
Purpose Gaussian combination membership function.
Synopsis y = gauss2mf(x,[sig1 c1 sig2 c2])
Description The Gaussian function depends on two parameters sig and c as given by
Thefunction gauss2mf is a combination of twoof these. Thefirst function,
specifiedbysig1 andc1, determines theshapeof theleftmost curve. Thesecond
function specified by sig2 and c2 determines theshapeof theright-most curve.
Whenever c1 <c2, thegauss2mf function reaches a maximumvalueof 1.
Otherwise, themaximumvalueis less than one. Theparameters arelisted in
theorder:
[sig1, c1, sig2, c2].
f x ; c , ( ) e
x c ( )
2
2
2
----------------------
=
gauss2mf
3-33
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');
See Also dsigmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf, trapmf,
trimf, zmf
gaussmf
3-34
3gaussmf
Purpose Gaussian curvebuilt-in membership function.
Synopsis y = gaussmf(x,[sig c])
Description ThesymmetricGaussian function dependson twoparameters andcasgiven
by
Theparameters for gaussmf represent theparameters and c listed in order
in thevector [sig c].
Example x=0:0.1:10;
y=gaussmf(x,[2 5]);
plot(x,y)
xlabel('gaussmf, P=[2 5]')
See Also dsigmf, gaussmf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf, trapmf,
trimf, zmf

f x ; c , ( ) e
x c ( )
2
2
2
----------------------
=

0 2 4 6 8 10
0
0.25
0.5
0.75
1
gaussmf, P = [2 5]
gbellmf
3-35
3gbellmf
Purpose Generalized bell-shaped built-in membership function.
Synopsis y = gbellmf(x,params)
Description Thegeneralizedbell function depends on threeparameters a, b, andcas given
by
wheretheparameter b is usually positive. Theparameter c locates thecenter
of thecurve. Enter theparameter vector params, thesecond argument for
gbellmf, as thevector whoseentries area, b, and c, respectively.
Example x=0:0.1:10;
y=gbellmf(x,[2 4 6]);
plot(x,y)
xlabel('gbellmf, P=[2 4 6]')
See Also dsigmf, gaussmf, gauss2mf, evalmf, mf2mf, pimf, psigmf, sigmf, smf, trapmf,
trimf, zmf
f x a ; b c , , ( )
1
1
x c
a
-----------
2b
+
------------------------------ =
0 2 4 6 8 10
0
0.25
0.5
0.75
1
gbellmf, P = [2 4 6]
genfis1
3-36
3genfis1
Purpose Generatean FI S structurefromdata without data clustering.
Synopsis fismat = genfis1(data)
fismat = genfis1(data,numMFs,inmftype, outmftype)
Description genfis1 generates a Sugeno-typeFI S structureused as initial conditions
(initialization of themembership function parameters) for anfis training.
genfis1(data, numMFs, inmftype, outmftype) generates aFI S structurefroma
trainingdata set, data, usinga grid partition on thedata (noclustering).
Thearguments for genfis1 areas follows:
data is thetrainingdatamatrix, which must beenteredwith all but thelast
columns representinginput data, and thelast column representingthe
singleoutput.
numMFs is a vector whosecoordinates specify thenumber of membership
functions associated with each input. I f you want thesamenumber of
membership functions tobeassociated with each input, then it suffices to
makenumMFs a singlenumber.
inmftype is a stringarray in which each rowspecifies themembership
function typeassociated with each input. Again, this can bea
one-dimensional singlestringif thetypeof membershipfunctionsassociated
with each input is thesame.
outmftype isastringthat specifiesthemembershipfunctiontypeassociated
with theoutput. Therecan only beoneoutput, sincethis is a Sugeno-type
system. Theoutput membership function typemust beeither linear or
constant.
Thenumber of membership functions associated with theoutput is thesame
as thenumber of rules generated by genfis1. Thedefault number of
membership functions, numMFs, is 2; thedefault input or output membership
function typeis 'gbellmf'. Theseareused whenever genfis1 is invoked
without thelast threearguments.
genfis1
3-37
Example data = [rand(10,1) 10*rand(10,1)-5 rand(10,1)];
numMFs = [3 7];
mfType = str2mat('pimf','trimf');
fismat = genfis1(data,numMFs,mfType);
[x,mf] = plotmf(fismat,'input',1);
subplot(2,1,1), plot(x,mf);
xlabel('input 1 (pimf)');
[x,mf] = plotmf(fismat,'input',2);
subplot(2,1,2), plot(x,mf);
xlabel('input 2 (trimf)');
See Also anfis
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0
0.2
0.4
0.6
0.8
1
input 1 (pimf )
5 4 3 2 1 0 1 2 3 4 5
0
0.2
0.4
0.6
0.8
1
input 2 (trimf)
genfis2
3-38
3genfis2
Purpose Generatean FI S structurefromdata usingsubtractiveclustering.
Synopsis fismat = genfis2(Xin,Xout,radii)
fismat = genfis2(Xin,Xout,radii,xBounds)
fismat = genfis2(Xin,Xout,radii,xBounds,options)
Description Given separatesets of input and output data, genfis2 generates an FI S using
fuzzy subtractiveclustering. When thereis only oneoutput, genfis2 may be
used togeneratean initial FI S for anfis trainingby first implementing
subtractiveclusteringon thedata. genfis2 accomplishes this by extractinga
set of rules that models thedata behavior. Theruleextraction method first
uses thesubclust function todeterminethenumber of rules and antecedent
membership functions and then uses linear least squares estimation to
determineeach rules consequent equations. This function returns an FI S
structurethat contains a set of fuzzy rules tocover thefeaturespace.
Thearguments for genfis2 areas follows:
Xin is a matrix in which each rowcontains theinput values of a data point.
Xout isamatrixinwhicheachrowcontainstheoutput valuesof adatapoint.
radii is avector that specifies acluster centers rangeof influencein each of
thedata dimensions, assumingthedata falls within a unit hyperbox. For
example, if thedata dimension is 3 (e.g., Xin has twocolumns and Xout has
onecolumn), radii =[0.50.40.3] specifies that theranges of influencein the
first, second, and third data dimensions (i.e., thefirst column of Xin, the
secondcolumn of Xin, andthecolumn of Xout) are0.5, 0.4, and0.3times the
width of thedata space, respectively. I f radii is a scalar, then thescalar
valueis applied toall data dimensions, i.e., each cluster center will havea
spherical neighborhood of influencewith thegiven radius.
xBounds isa2-by-N optional matrixthat specifieshowtomapthedatainXin
andXout intoaunit hyperbox, whereN isthedata(row) dimension. Thefirst
rowof xBounds contains theminimumaxis rangevalues andthesecondrow
contains themaximumaxis rangevalues for scalingthedata in each
dimension. For example, xBounds =[-10 0 -1; 10 50 1] specifies that data
values in thefirst data dimension aretobescaled fromtherange[-10 +10]
intovalues in therange[0 1]; data values in thesecond data dimension are
tobescaled fromtherange[0 50]; and data values in thethird data
genfis2
3-39
dimension aretobescaled fromtherange[-1 +1]. I f xBounds is an empty
matrix or not provided, then xBounds defaults totheminimumand
maximumdata values found in each data dimension.
options isanoptional vector for specifyingalgorithmparameterstooverride
thedefault values. Theseparameters areexplained in thehelp text for
subclust onpage3-72. Default valuesareinplacewhenthisargument isnot
specified.
Examples fismat = genfis2(Xin,Xout,0.5)
This is theminimumnumber of arguments neededtousethis function. Herea
rangeof influenceof 0.5 is specified for all data dimensions.
fismat = genfis2(Xin,Xout,[0.5 0.25 0.3])
This assumes thecombineddatadimension is 3. SupposeXin has twocolumns
andXout hasonecolumn, then 0.5and0.25aretherangesof influencefor each
of theXin data dimensions, and 0.3is therangeof influencefor theXout data
dimension.
fismat = genfis2(Xin,Xout,0.5,[-10 -5 0; 10 5 20])
This specifies howtonormalizethedata in Xin and Xout intovalues in the
range[0 1] for processing. SupposeXin has twocolumns and Xout has one
column, then thedata in thefirst column of Xin arescaled from[-10 +10], the
data in thesecond column of Xin arescaled from[-5 +5], and thedata in Xout
arescaled from[0 20].
See Also subclust
gensurf
3-40
3gensurf
Purpose Generatean FI S output surface.
Synopsis gensurf(fis)
gensurf(fis,inputs,output)
gensurf(fis,inputs,output,grids,refinput)
Description gensurf(fis) generates a plot of theoutput surfaceof a given fuzzy inference
system(fis) usingthefirst twoinputs and thefirst output.
gensurf(fis,inputs,output) generates a plot usingtheinputs (oneor two)
andoutput (onlyoneis allowed) given, respectively, bythevector, inputs, and
thescalar, output.
gensurf(fis,inputs,output,grids) allowsyoutospecifythenumber of grids
in theX (first, horizontal) and Y (second, vertical) directions. I f grids is a two
element vector, thegrids in theX and Y directions can beset independently.
gensurf(fis,inputs,output,grids,refinput) can beused if therearemore
than twooutputs. Thelength of thevector refinput is thesameas thenumber
of inputs.
Enter NaNs for theentries of refinput correspondingtotheinputs whose
surfaceis beingdisplayed.
Enter real doublescalars tofix thevalues of other inputs.
[x,y,z]=gensurf(...) returns thevariables that definetheoutput surface
and suppresses automatic plotting.
gensurf
3-41
Example 1 a = readfis('tipper');
gensurf(a)
Example 2 a = gensurf(Temp,[1 2],1,[20 20],[nan nan 0.2]);
generates thesurfaceof athree-input FI S namedTemp fromits first twoinputs
toits first output, whilefixinga referencevaluefor thethird input at .2.
See Also evalfis, surfview
0
2
4
6
8
10
0
2
4
6
8
10
5
10
15
20
25
service
food
t
i
p
getfis
3-42
3getfis
Purpose Get fuzzy systemproperties.
Synopsis getfis(a)
getfis(a,'fisprop')
getfis(a,'vartype',varindex,'varprop')
getfis(a,'vartype',varindex,'mf',mfindex)
getfis(a,'vartype',varindex,'mf',mfindex,'mfprop')
Description This is thefundamental access function for theFI S structure. With this one
function you can learn about every part of thefuzzy inferencesystem.
Thearguments for getfis areas follows:
a: thenameof a workspacevariableFI S structure.
'vartype': a stringindicatingthetypeof variableyou want (input or
output).
varindex: an integer indicatingtheindex of thevariableyou want (1, for
input 1, for example).
'mf': a required stringthat indicates you aresearchingfor membership
function information.
mfindex: theindex of themembership function for which you areseeking
information.
getfis
3-43
Examples Oneinput argument (output is theempty set)
a = readfis('tipper');
getfis(a)
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
Twoinput arguments
getfis(a,'type')
ans =
mamdani
Threeinput arguments (output is theempty set)
getfis(a,'input',1)
Name = service
NumMFs = 3
MFLabels =
poor
good
excellent
Range = [0 10]
Four input arguments
getfis(a,'input',1,'name')
ans =
service
getfis
3-44
Fiveinput arguments
getfis(a,'input',1,'mf',2)
Name = good
Type = gaussmf
Params =
1.5000 5.0000
Six input arguments
getfis(a,'input',1,'mf',2,'name')
ans =
good
See Also setfis, showfis
mam2sug
3-45
3mam2sug
Purpose TransformMamdani FI S intoa SugenoFI S.
Synopsis sug_fis=mam2sug(mam_fis)
Description mam2sug(mam_fis) transforms a (not necessarily singleoutput) Mamdani FI S
structuremam_fis intoa SugenoFI S structuresug_fis. Thereturned Sugeno
systemhas constant output membership functions. Theseconstants are
determined by thecentroids of theconsequent membership functions of the
original Mamdani system. Theantecedent remains unchanged.
Examples mam_fismat = readfis('mam22.fis');
sug_fismat = mam2sug(mam_fismat);
subplot(2,2,1); gensurf(mam_fismat, [1 2], 1);
title('Mamdani system (Output 1)');
subplot(2,2,2); gensurf(sug_fismat, [1 2], 1);
title('Sugeno system (Output 1)');
subplot(2,2,3); gensurf(mam_fismat, [1 2], 2);
title('Mamdani system (Output 2)');
subplot(2,2,4); gensurf(sug_fismat, [1 2], 2);
title('Sugeno system (Output 2)');
mf2mf
3-46
3mf2mf
Purpose Translates parameters between membership functions.
Synopsis outParams = mf2mf(inParams,inType,outType)
Description This function translates any built-in membership function typeintoanother,
in terms of its parameter set. I n principle, mf2mf mimics thesymmetry points
for both thenewand old membership functions. Occasionally this translation
resultsinlost information, sothat if theoutput parametersaretranslatedback
intotheoriginal membership function type, thetransformed membership
function will not look thesameas it did originally.
Theinput arguments for mf2mf areas follows:
inParams: theparameters of themembership function you aretransforming
inType: a stringnamefor thetypeof membership function you are
transforming
outType: a stringnamefor thenewmembership function you are
transformingto
Examples x=0:0.1:5;
mfp1 = [1 2 3];
mfp2 = mf2mf(mfp1,'gbellmf','trimf');
plot(x,gbellmf(x,mfp1),x,trimf(x,mfp2))
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, pimf, psigmf, sigmf, smf,
trapmf, trimf, zmf
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
mfedit
3-47
3mfedit
Purpose Membership function editor.
Synopsis mfedit('a')
mfedit(a)
mfedit
Description
mfedit('a') generates a membership function editor that allows you to
inspect andmodifyall themembershipfunctions for your FI S storedin thefile,
a.fis.
mfedit(a) operates on a MATLAB workspacevariable, for a FI S structure, a.
mfedit alonebrings up themembership function editor with noFI S loaded.
For each membership function you can changethename, thetype, and the
parameters. Eleven built-in membership functions areprovided for you to
choosefrom, although of courseyou can always createyour own specialized
versions. Refer toTheMembership Function Editor on page2-52 for more
information about howtousemfedit.
mfedit
3-48
Select theicon for thevariableon theupper left sideof thediagram(under the
headingFI S Variables) todisplayits associatedmembershipfunctions in the
plot region. Select membership functions by clickingonceon themor their
labels.
Menu Items On theMembership Function Editor, thereis a menu bar that allows you to
open related GUI tools, open and savesystems, and soon. TheFilemenu for
theMembership Function Editor is thesameas theonefound on theFI S
Editor. Refer tofuzzy on page3-29 for moreinformation.
Under Edit, select:
Add MF... toadd membership functions tothecurrent variable.
Add customMF... toadd a customized membership function tothecurrent
variable.
Removecurrent MF todeletethecurrent membership function.
Removeall MFs todeleteall membership functions of thecurrent variable.
Undo toundothemost recent change.
Under View, select:
Edit FIS properties... toinvoketheFI S Editor.
Edit rules... toinvoketheRuleEditor.
Viewrules... toinvoketheRuleViewer.
Viewsurface... toinvoketheSurfaceViewer.
Membership
Function
Pop-up Menu
Thereare11 built-in membership functions tochoosefrom, and you alsohave
theoption of installinga customized membership function.
See Also fuzzy, ruleedit, ruleview, surfview
newfis
3-49
3newfis
Purpose CreatenewFI S.
Synopsis a=newfis(fisName,fisType,andMethod,orMethod,impMethod, ...
aggMethod,defuzzMethod)
Description This function creates newFI S structures. newfis has up toseven input
arguments, and theoutput argument is an FI S structure. Theseven input
arguments areas follows:
fisName is thestringnameof theFI S structure, fisName.fis you create.
fisType is thetypeof FI S.
andMethod, orMethod, impMethod, aggMethod, and defuzzMethod,
respectivelyprovidethemethodsfor AND, OR, implication, aggregation, and
defuzzification.
Examples Thefollowingexampleshows what thedefaults arefor each of themethods:
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
DefuzzMethod centroid
ans =
[newsys]
See Also readfis, writefis
parsrule
3-50
3parsrule
Purpose Parsefuzzy rules.
Synopsis fis2 = parsrule(fis,txtRuleList)
fis2 = parsrule(fis,txtRuleList,ruleFormat)
fis2 = parsrule(fis,txtRuleList,ruleFormat,lang)
Description This function parses thetext that defines therules (txtRuleList) for a
MATLAB workspaceFI S variable, fis, and returns a FI S structurewith the
appropriaterulelist in place. I f theoriginal input FI S structure, fis, has any
rules initially, they arereplaced in thenewstructure, fis2. Threedifferent
ruleformats (indicated by ruleFormat) aresupported: 'verbose', symbolic,
and indexed.Thedefault format is verbose. When theoptional language
argument, lang, is used, therules areparsed in verbosemode, assumingthe
key words arein thelanguage, lang. This languagemust beeither 'english',
'francais', or 'deutsch'. ThekeylanguagewordsinEnglishare: if, then, is, AND,
OR, and NOT.
Examples 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)
See Also addrule, ruleedit, showrule
pimf
3-51
3pimf
Purpose -shaped built-in membership function.
Synopsis y = pimf(x,[a b c d])
Description This spline-basedcurveis sonamedbecauseof its -shape. This membership
function is evaluatedat thepoints determinedbythevector x. Theparameters
a and d locatethefeet of thecurve, whileb and c locateits shoulders.
Examples x=0:0.1:10;
y=pimf(x,[1 4 5 10]);
plot(x,y)
xlabel('pimf, P=[1 4 5 10]')
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, psigmf, sigmf, smf,
trapmf, trimf, zmf

0 2 4 6 8 10
0
0.25
0.5
0.75
1
pimf, P = [1 4 5 10]
plotfis
3-52
3plotfis
Purpose Plot an FI S.
Synopsis plotfis(fismat)
Description This function displays ahigh level diagramof an FI S, fismat. I nputs andtheir
membership functions appear totheleft of theFI S structural characteristics,
whileoutputs and their membership functions appear on theright.
Examples a = readfis('tipper');
plotfis(a)
See Also evalmf, plotmf
plotmf
3-53
3plotmf
Purpose Plot all of themembership functions for a given variable.
Synopsis plotmf(fismat,varType,varIndex)
Description This function plots all of themembership functions in theFI S called fismat
associated with a given variablewhosetypeand index arerespectively given
by varType ('input' or 'output'), and varIndex. This function can alsobe
used with theMATLAB function, subplot.
Examples a = readfis('tipper');
plotmf(a,'input',1)
See Also evalmf, plotfis
0 1 2 3 4 5 6 7 8 9 10
0
0.2
0.4
0.6
0.8
1
service
D
e
g
r
e
e

o
f

b
e
l
i
e
f
poor good excellent
psigmf
3-54
3psigmf
Purpose Built-in membership function composed of theproduct of two
sigmoidally-shaped membership functions.
Synopsis y = psigmf(x,[a1 c1 a2 c2])
Description Thesigmoid curveplotted for thevector x depends on twoparameters a and c
as given by
psigmf is simply theproduct of twosuch curves plotted for thevalues of the
vector x
f
1
(x; a1, c
1
) * f
2
(x; a2, c
2
)
Theparameters arelisted in theorder: [a1 c
1
a
2
c
2
].
Examples x=0:0.1:10;
y=psigmf(x,[2 3 -5 8]);
plot(x,y)
xlabel('psigmf, P=[2 3 -5 8]')
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, sigmf, smf, trapmf,
trimf, zmf
f x a ; c , ( )
1
1 e
a x c ( )
+
------------------------------- =
0 2 4 6 8 10
0
0.25
0.5
0.75
1
psigmf, P = [2 3 5 8]
readfis
3-55
3readfis
Purpose Load an FI S fromthedisk.
Synopsis fismat = readfis('filename')
Description Read a fuzzy inferencesystemfroma .fis file(named filename) on thedisk
and bringtheresultingfileintotheworkspace.
fismat = readfis (noinput arguments) brings up a uigetfile dialogbox to
assist with thenameand directory location of thefile.
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 writefis
rmmf
3-56
3rmmf
Purpose Toremovemembership function froman FI S.
Synopsis fis = rmmf(fis,'varType',varIndex,'mf',mfIndex)
Description fis = rmmf(fis,varType,varIndex,'mf',mfIndex) removesthemembership
function, mfIndex, of variabletype, varType, of index varIndex, fromthefuzzy
inferencesystemassociated with theworkspaceFI S structure, fis:
ThestringvarType must be'input' or 'output'.
varIndex isaninteger for theindexof thevariable. Thisindexrepresentsthe
order in which thevariables arelisted.
Theargument 'mf' is a stringrepresentingthemembership function.
mfIndex is an integer for theindex of themembership function. This index
represents theorder in which themembership functions arelisted.
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
NumMFs = 0
MFLabels =
Range = [0 100]
See Also addmf, addrule, addvar, plotmf, rmvar
rmvar
3-57
3rmvar
Purpose Toremovevariables froman FI S.
Synopsis [fis2,errorStr] = rmvar(fis,'varType',varIndex)
fis2 = rmvar(fis,'varType',varIndex)
Description fis2 = rmvar(fis,'varType',varIndex) removes thevariable'varType', of
index varIndex, fromthefuzzy inferencesystemassociated with the
workspaceFI S structure, fis:
ThestringvarType must be'input' or 'output'.
varIndex isaninteger for theindexof thevariable. Thisindexrepresentsthe
order in which thevariables arelisted.
[fis2,errorStr] = rmvar(fis,'varType',varIndex) returns any error
messages tothestring, errorStr.
This commandautomaticallyalters therulelist tokeepits sizeconsistent with
thecurrent number of variables. You must deletefromtheFI S any rulethat
contains avariableyou want toremove, beforeremovingit. You cannot remove
a fuzzy variablecurrently in usein therulelist.
Examples a = newfis('mysys');
a = addvar(a,'input','temperature',[0 100]);
getfis(a)
rmvar
3-58
returns
Name = mysys
Type = mamdani
NumInputs = 1
InLabels =
temperature
NumOutputs = 0
OutLabels =
NumRules = 0
AndMethod = min
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 addmf, addrule, addvar, rmmf
ruleedit
3-59
3ruleedit
Purpose Ruleeditor and parser.
Synopsis ruleedit('a')
ruleedit(a)
Description
TheRuleEditor, when invoked usingruleedit('a'), is used tomodify the
rules of an FI S structurestored in a file, a.fis. I t can alsobeused toinspect
therules beingused by a fuzzy inferencesystem.
Tousethis editor tocreaterules, you must first defineall of theinput and
output variables you want tousewith theFI S editor. You can createtherules
usingthelistbox and check box choices for input and output variables,
connections, and weights. Refer toTheRuleEditor on page2-56 for more
information about howtouseruleedit.
Thesyntax ruleedit(a) is used when you want tooperateon a workspace
variablefor an FI S structurecalled a.
Language and Format
are options on this
GUI. Languages are
English, Deutsch, and
Francais. Formats are
verbose, symbolic,
and indexed.
ruleedit
3-60
Menu Items On theRuleEditor, thereis a menu bar that allows you toopen related GUI
tools, open and savesystems, and soon. TheFilemenu for theRuleEditor is
thesameas theonefound on theFI S Editor. Refer tofuzzy on page3-29 for
moreinformation.
UsethefollowingEdit menu item:
Undo toundothemost recent change.
UsethefollowingViewmenu items:
Edit FIS properties... toinvoketheFI S Editor.
Edit membership functions... toinvoketheMembership Function
Editor.
Viewrules... toinvoketheRuleViewer.
Viewsurface... toinvoketheSurfaceViewer.
UsetheOptions menu items:
Languagetoselect thelanguage: English, Deutsch, and Francais
Format toselect theformat:
` verboseuses thewords if, then, AND, OR, and soon tocreate
actual sentences.
` symbolic substitutes somesymbols for thewords used in theverbose
mode. For example, if A AND B then C becomes A & B =>C.
` indexed mirrors howtheruleis stored in theFI S structure.
See Also addrule, fuzzy, mfedit, parsrule, ruleview, showrule, surfview
ruleview
3-61
3ruleview
Purpose Ruleviewer and fuzzy inferencediagram.
Synopsis ruleview('a')
Description
TheRuleViewer invoked usingruleview('a') depicts thefuzzy inference
diagramfor an FI S stored in a file, a.fis. I t is used toviewtheentire
implication process frombeginningtoend. You can movearound theline
indices that correspond totheinputs and then watch thesystemreadjust and
computethenewoutput. Refer toTheRuleViewer on page2-59 for more
information about howtouseruleview.
Menu Items On theRuleViewer, thereis a menu bar that allows you toopen related GUI
tools, open and savesystems, and soon. TheFilemenu for theRuleViewer is
ruleview
3-62
thesameas theonefound on theFI S Editor. Refer tofuzzy on page3-29 for
moreinformation.
UsetheViewmenu items:
Edit FIS properties... toinvoketheFI S Editor
Edit membership functions... toinvoketheMembership Function Editor
Edit rules... toinvoketheRuleEditor
Viewsurface... toinvoketheSurfaceViewer
UsetheOptions menu item:
Ruledisplay format toset theformat in which theruleappears. I f you
click on therulenumbers on theleft sideof thefuzzy inferencediagram,
theruleassociated with that number will appear in theStatus Bar at the
bottomof theRuleViewer.
See Also fuzzy, mfedit, ruleedit, surfview
setfis
3-63
3setfis
3
Purpose Set fuzzy systemproperties.
Synopsis a = setfis(a,'fispropname','newfisprop')
a = setfis(a,'vartype',varindex,'varpropname','newvarprop')
a = setfis(a,'vartype',varindex,'mf',mfindex, ...
'mfpropname','newmfprop');
Description Thecommandsetfis can becalledwith three, five, or seven input arguments,
dependingon whether you want toset a property of theentireFI S structure,
for a particular variablebelongingtothat FI S structure, or for a particular
membership function belongingtooneof thosevariables. Thearguments are:
a a variablenameof an FI S fromtheworkspace
'vartype' a stringindicatingthevariabletype: input or output
varindex theindex of theinput or output variable
'mf' a required stringfor thefourth argument of a 7-argument call for
setfis, indicatingthis variableis a membership function
mfindex theindex of themembership function belongingtothechosen
variable
'fispropname' a stringindicatingtheproperty of theFI S field you want
toset: name, type, andmethod, ormethod, impmethod, aggmethod,
defuzzmethod
'newfisprop' a stringdescribingthenameof theFI S property or method
you want toset
'varpropname' astringindicatingthenameof thevariablefieldyou want
toset: name or range
'newvarprop' astringdescribingthenameof thevariableyou want toset
(for name), or an array describingtherangeof that variable(for range)
'mfpropname' a stringindicatingthenameof themembership function
field you want toset: name, type, or params.
'newmfprop' a stringdescribingthenameor typeof themembership
function fieldwant toset (for name or type), or an array describingtherange
of theparameters (for params)
setfis
3-64
Examples Called with threearguments,
a = readfis('tipper');
a2 = setfis(a, 'name', 'eating');
getfis(a2, 'name');
Results in
out =
eating
I f used with fivearguments, setfis will updatetwovariableproperties.
a2 = setfis(a,'input',1,'name','help');
getfis(a2,'input',1,'name')
ans =
help
I f used with seven arguments, setfis will updateany of several membership
function properties.
a2 = setfis(a,'input',1,'mf',2,'name','wretched');
getfis(a2,'input',1,'mf',2,'name')
ans =
wretched
See Also getfis
sffis
3-65
3sffis
Purpose Fuzzy inferenceS-function for Simulink.
Synopsis output = sffis(t,x,u,flag,fismat)
Description This MEX-fileis used by Simulink toundertakethecalculation normally
performed by evalfis. I t has been optimized towork in theSimulink
environment. This means, amongother things, that sffis builds a data
structurein memory duringtheinitialization phaseof a Simulink simulation,
which it then continues touseuntil thesimulation is complete.
Thearguments t, x, and flag arestandard Simulink S-function arguments
(seeChapter 8, S-Functions in theUsingSimulink documentation). The
argument u is theinput totheMATLAB workspaceFI S structure, fismat. I f,
for example, therearetwoinputs tofismat, then u will bea two-element
vector.
See Also evalfis, fuzblock
showfis
3-66
3showfis
Purpose Display annotated FI S.
Synopsis showfis(fismat)
Description showfis(fismat) prints a version of theMATLAB workspacevariableFI S,
fismat, allowingyou toseethesignificanceand contents of each field of the
structure.
Examples a = readfis('tipper');
showfis(a)
returns
1. Name tipper
2. Type mamdani
3. Inputs/Outputs [2 1]
4. NumInputMFs [3 2]
5. NumOutputMFs 3
6. NumRules 3
7. AndMethod min
8. OrMethod max
9. ImpMethod min
10. AggMethod max
11. DefuzzMethod centroid
12. InLabels service
13. food
14. OutLabels tip
15. InRange [0 10]
16. [0 10]
17. OutRange [0 30]
18. InMFLabels poor
19. good
20. excellent
21. rancid
22. delicious
23. OutMFLabels cheap
24. average
25. generous
26. InMFTypes gaussmf
27. gaussmf
showfis
3-67
28. gaussmf
29. trapmf
30. trapmf
31. OutMFTypes trimf
32. trimf
33. trimf
34. InMFParams [1.5 0 0 0]
35. [1.5 5 0 0]
36. [1.5 10 0 0]
37. [0 0 1 3]
38. [7 9 10 10]
39. OutMFParams [0 5 10 0]
40. [10 15 20 0]
41. [20 25 30 0]
42. Rule Antecedent [1 1]
43. [2 0]
44. [3 2]
42. Rule Consequent 1
43. 2
44. 3
42. Rule Weigth 1
43. 1
44. 1
42. Rule Connection 2
43. 1
44. 2
See Also getfis
showrule
3-68
3showrule
Purpose Display FI S rules.
Synopsis showrule(fis)
showrule(fis,indexList)
showrule(fis,indexList,format)
showrule(fis,indexList,format,Lang)
Description This command is used todisplay therules associated with a given system. I t
can beinvoked with onetofour arguments. Thefirst argument, fis, is
required. This is theMATLAB workspacevariablenamefor a FI S structure.
Thesecond (optional) argument indexList is thevector of rules you want to
display. Thethirdargument (optional) is thestringrepresentingtheformat in
which therules arereturned. showrule can return therulein any of three
different formats: 'verbose' (thedefault mode, for which English is thedefault
language), 'symbolic', and 'indexed', for membership function index
referencing.
When used with four arguments, theforth argument must beverbose, and
showrule(fis,indexList,format,lang) displays therules in thelanguage
given by lang, which must beeither 'english', 'francais', or 'deutsch'.
showrule
3-69
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)
1. (service==poor) | (food==rancid) => (tip=cheap) (1)
showrule(a,1:3,'indexed')
ans =
1 1, 1 (1) : 2
2 0, 2 (1) : 1
3 2, 3 (1) : 2
See Also parsrule, ruleedit, addrule
sigmf
3-70
3sigmf
Purpose Sigmoidally-shaped built-in membership function.
Synopsis y = sigmf(x,[a c])
Description Thesigmoidal function, sigmf(x,[a c]), as given belowby , is a
mappingon a vector x, and depends on twoparameters a and c:
Dependingon thesign of theparameter a, thesigmoidal membershipfunction
is inherently open totheright or totheleft, and thus is appropriatefor
representingconcepts such as very largeor very negative.More
conventional-lookingmembership functions can bebuilt by takingeither the
product or differenceof twodifferent sigmoidal membershipfunctions. You can
find out moreabout this in this chapters entries for dsigmf and psigmf.
Examples x=0:0.1:10;
y=sigmf(x,[2 4]);
plot(x,y)
xlabel('sigmf, P=[2 4]')
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, smf,
trapmf, trimf, zmf
f x a c , , ( )
f x a c , , ( )
1
1 e
a x c ( )
+
------------------------------- =
0 2 4 6 8 10
0
0.25
0.5
0.75
1
sigmf, P = [2 4]
smf
3-71
3smf
Purpose Sshaped built-in membership function.
Synopsis y = smf(x,[a b])
Description This spline-based curveis a mappingon thevector x, and is named becauseof
its Sshape. Theparameters a and blocatetheextremes of thesloped portion
of thecurve.
Examples x=0:0.1:10;
y=smf(x,[1 8]);
plot(x,y)
xlabel('smf, P=[1 8]')
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf,
trapmf, trimf, zmf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
smf, P = [1 8]
subclust
3-72
3subclust
Purpose Find cluster centers with subtractiveclustering.
Synopsis [C,S] = subclust(X,radii,xBounds,options)
Description This function estimates thecluster centers in a set of data by usingthe
subtractiveclusteringmethod. Thesubtractiveclusteringmethod assumes
each data point is a potential cluster center and calculates a measureof the
likelihood that each data point would definethecluster center, based on the
density of surroundingdata points. Thealgorithm
Selects thedatapoint with thehighest potential tobethefirst cluster center
Removes all data points in thevicinity of thefirst cluster center (as
determined by radii), in order todeterminethenext data cluster and its
center location
I terates on this process until all of thedatais within radii of acluster center
Thesubtractiveclusteringmethod is an extension of themountain clustering
method proposed by R. Yager.
Thematrix X contains thedata tobeclustered; each rowof X is a data point.
Thevariableradii isavector of entriesbetween0and1that specifiesacluster
centers rangeof influencein each of thedata dimensions, assumingthedata
falls within a unit hyperbox. Small radii values generally result in findinga
fewlargeclusters. Good values for radii areusually between 0.2 and 0.5.
For example, if thedata dimension is two(X has twocolumns),
radii =[0.5 0.25] specifies that therangeof influencein thefirst data
dimension is half thewidth of thedata spaceand therangeof influencein the
second data dimension is onequarter thewidth of thedata space. I f radii is a
scalar, then thescalar valueis appliedtoall datadimensions, i.e., each cluster
center will havea spherical neighborhood of influencewith thegiven radius.
xBounds is a 2-by-N matrix that specifies howtomap thedata in X intoa unit
hyperbox, whereN is thedata dimension. This argument is optional if X is
alreadynormalized. Thefirst rowcontainstheminimumaxisrangevaluesand
thesecondrowcontains themaximumaxis rangevalues for scalingthedatain
eachdimension. For example, xBounds =[-10-5; 105] specifiesthat datavalues
in thefirst datadimension aretobescaledfromtherange[-10+10] intovalues
in therange[0 1]; data values in thesecond data dimension aretobescaled
fromtherange[-5 +5] intovalues in therange[0 1]. I f xBounds is an empty
subclust
3-73
matrix or not provided, then xBounds defaults totheminimumand maximum
data values found in each data dimension.
Theoptions vector can beusedfor specifyingclusteringalgorithmparameters
tooverridethedefault values. Thesecomponents of thevector options are
specified as follows:
options(1) = quashFactor: This is thefactor used tomultiply theradii
values that determinetheneighborhood of a cluster center, soas toquash
thepotential for outlyingpoints tobeconsidered as part of that cluster.
(default: 1.25)
options(2) = acceptRatio: This sets thepotential, as a fraction of the
potential of thefirst cluster center, abovewhich another data point will be
accepted as a cluster center. (default: 0.5)
options(3) = rejectRatio: This sets thepotential, as a fraction of the
potential of thefirst cluster center, belowwhich adatapoint will berejected
as a cluster center. (default: 0.15)
options(4) = verbose: I f this termis not zero, then progress information
will beprinted as theclusteringprocess proceeds. (default: 0)
Thefunction returns thecluster centers in thematrix C; each rowof C contains
thepositionof acluster center. ThereturnedS vector containsthesigmavalues
that specify therangeof influenceof a cluster center in each of thedata
dimensions. All cluster centers sharethesameset of sigma values.
Examples [C,S] = subclust(X,0.5)
Thisistheminimumnumber of argumentsneededtousethisfunction. A range
of influenceof 0.5 has been specified for all data dimensions.
[C,S] = subclust(X,[0.5 0.25 0.3],[],[2.0 0.8 0.7])
This assumes thedata dimension is 3 (X has 3 columns) and uses a rangeof
influenceof 0.5, 0.25, and 0.3 for thefirst, second and third data dimension,
respectively. Thescalingfactors for mappingthedataintoaunit hyperboxwill
beobtained fromtheminimumand maximumdata values. ThesquashFactor
is set to2.0, indicatingthat weonlywant tofindclusters that arefar fromeach
other. TheacceptRatio is set to0.8, indicatingthat wewill only accept data
points that havea very strongpotential for beingcluster centers. The
subclust
3-74
rejectRatio is set to0.7, indicatingthat wewant toreject all data points
without a strongpotential.
See Also genfis2
References Chiu, S., FuzzyModel I dentification Basedon Cluster Estimation,J ournal of
I ntelligent & Fuzzy Systems, Vol. 2, No. 3, Sept. 1994.
Yager, R. and D. Filev, Generation of Fuzzy Rules by Mountain Clustering,
J ournal of I ntelligent & Fuzzy Systems, Vol. 2, No. 3, pp. 209-219, 1994.
surfview
3-75
3surfview
Purpose Output surfaceviewer.
Synopsis surfview('a')
Description
TheSurfaceViewer invoked usingsurfview('a') is a GUI tool that lets you
examinetheoutput surfaceof an FI S storedin afile, a.fis, for any oneor two
inputs. Sinceit does not alter thefuzzy systemor its associated FI S structure
in any way, it is aread-only editor. Usingthepop-upmenus, you select thetwo
input variables you want assigned tothetwoinput axes (X and Y), as well the
output variableyou want assigned totheoutput (or Z) axis. Select the
Evaluatebutton toperformthecalculation and plot theoutput surface.
By clickingon theplot axes and draggingthemouse, you can manipulatethe
surfacesothat you can viewit fromdifferent angles.
I f therearemorethan twoinputstoyour system, you must supplytheconstant
values associated with any unspecified inputs in thereferenceinput section.
Refer toTheSurfaceVieweron page2-61for moreinformation about howto
usesurfview.
surfview
3-76
Menu Items OntheSurfaceViewer, thereisamenubar that allowsyoutoopenrelatedGUI
tools, open andsavesystems, and soon. TheFilemenu for theSurfaceViewer
is thesameas theonefound on theFI S Editor. Refer tofuzzy on page3-29for
moreinformation.
UsetheViewmenu items:
Edit FIS properties... toinvoketheFI S Editor.
Edit membership functions... toinvoketheMembership Function Editor.
Edit rules... toinvoketheRuleEditor.
Viewrules... toinvoketheRuleViewer.
UsetheOptions menu items:
Plot tochooseamongeight different kinds of plot styles.
Color Map tochooseamongseveral different color schemes.
Always evaluatetoautomatically evaluateand plot a newsurfaceevery
timeyou makea changethat affects theplot (likechangingthenumber of
grid points). This is thedefault option. Todeselect this option, select it once
more.
See Also anfisedit, fuzzy, gensurf, mfedit, ruleedit, ruleview
trapmf
3-77
3trapmf
Purpose Trapezoidal-shaped built-in membership function.
Synopsis y = trapmf(x,[a b c d])
Description Thetrapezoidal curveis a function of a vector, x, and depends on four scalar
parameters a, b, c, and d, as given by
or, morecompactly, by
Theparameters a andd locatethefeetof thetrapezoidandtheparameters b
and c locatetheshoulders.
Examples x=0:0.1:10;
y=trapmf(x,[1 5 7 8]);
plot(x,y)
xlabel('trapmf, P=[1 5 7 8]')
f x a ; b c d , , , ( )
0, x a
x a
b a
------------, a x b
1, b x c
d x
d c
------------, c x d
0, d x





' ;





=
f x a ; b c d , , , ( ) max min
x a
b a
------------ 1
d x
d c
------------ , ,
,
_
0 ,
,
_
=
0 2 4 6 8 10
0
0.25
0.5
0.75
1
trapmf, P = [1 5 7 8]
trapmf
3-78
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf,
trimf, zmf
trimf
3-79
3trimf
Purpose Triangular-shaped built-in membership function.
Synopsis y = trimf(x,params)
y = trimf(x,[a b c])
Description Thetriangular curveis a function of a vector, x, and depends on threescalar
parameters a, b, and c, as given by
or, morecompactly, by
Theparameters a and c locatethefeetof thetriangleand theparameter c
locates thepeak.
Examples x=0:0.1:10;
y=trimf(x,[3 6 8]);
plot(x,y)
xlabel('trimf, P=[3 6 8]')
f x a ; b c , , ( )
0, x a
x a
b a
------------, a x b
c x
c b
------------, b x c
0, c x




' ;




=
f x a ; b c , , ( ) max min
x a
b a
------------
c x
c b
----------- - ,
,
_
0 ,
,
_
=
0 2 4 6 8 10
0
0.25
0.5
0.75
1
trimf, P = [3 6 8]
trimf
3-80
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf,
trapmf
writefis
3-81
3writefis
Purpose Savean FI S tothedisk.
Synopsis writefis(fismat)
writefis(fismat,'filename')
writefis(fismat,'filename','dialog'
Description writefis saves aMATLAB workspaceFI S structure, fismat, as a .fis fileon
disk.
writefis(fismat) brings up a dialogbox toassist with thenamingand
directory location of thefile.
writefis(fismat,'filename') writes a .fis filecorrespondingtotheFI S
structure, fismat, toadisk filecalledfilename.fis. Nodialogboxisusedand
thefileis saved tothecurrent directory.
writefis(fismat,'filename','dialog') brings up a dialogbox with the
default namefilename.fis supplied.
Theextension.fis isonlyaddedtofilename if it isnot alreadyincludedinthe
name.
Examples 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')
See Also readfis
zmf
3-82
3zmf
Purpose Z-shaped built-in membership function.
Synopsis y = zmf(x,[a b])
Description This spline-based function of x is sonamed becauseof its Z-shape. The
parameters a and b locatetheextremes of thesloped portion of thecurve.
Examples x=0:0.1:10;
y=zmf(x,[3 7]);
plot(x,y)
xlabel('zmf, P=[3 7]')
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf,
trapmf, trimf
0 2 4 6 8 10
0
0.25
0.5
0.75
1
zmf, P = [3 7]
I-1
Index
A
addmf 72, 76, 3-6
addrule 72, 76, 3-8
addvar 76, 3-9
aggregation 36, 40, 44, 60, 63, 86, 132, 133
AND 30, 37, 63, 103
ANFI S 93
anfis 7, 92, 95, 104, 109, 112, 114, 125, 3-10
options 116
ANFI S Editor GUI 7, 45, 92, 95, 106, 109, 114,
3-14
anfisedit 67, 93, 95, 3-14
antecedent 35, 37, 59, 74, 86, 88, 132
B
backpropagation 104
C
chaotic timeseries 120
checkingdata 94, 118
checkingerror 119
clustering120, 121, 128, 132
clusteringalgorithms 133
clusteringGUI 128
consequent 32, 35, 40, 59, 74, 86, 132
antecedent 37
convertfis 3-16
D
defuzz 3-17
defuzzification 32, 36, 40, 49, 63, 95, 132
defuzzify 32, 41
degreeof membership 20, 24, 33, 35, 38
distfcm 121
dsigmf 27, 3-18
E
error tolerance104
evalfis 73, 126, 3-19, 3-26
evalmf 3-21
F
fcm (fuzzy c-means) 120, 128, 3-22
findcluster 128, 3-24
FI S 43, 47, 49, 53, 58, 65, 67, 73, 84, 92, 95, 109,
125, 132, 3-10
C-code130
Editor 45, 49, 68, 115
files 76
generating100
Mamdani-type49, 86, 91
matrix 73
savinga FI S 62
structure93, 115, 117
Sugeno-type86, 88, 95
Sugeno-typeSeealsoSugeno-typeinference
97
fuzblock 83, 3-27
fuzdemos 3-28
fuzzification 32, 37, 42, 49, 132
fuzzy 3-29
fuzzy clustering115, 120
fuzzy c-means clustering3-22
Fuzzy I nferenceSystem(FI S) 19, 45, 132
fuzzy operators 29, 32, 37, 39, 44, 58, 63, 71, 131
fuzzy set 20, 23, 26, 35, 38, 40, 60, 86, 88, 132
Index
I-2
G
gauss2mf 27, 3-32
gaussian 27
gaussmf 27, 3-34
gbellmf 27, 3-35
genfis 111
genfis1 101, 3-36
genfis2 101, 126, 3-38
gensurf 70, 88, 90, 3-40
getfis 66, 76, 89, 3-42
glossary 132
grid partition 100
H
hybrid method 104
I
if-then rules 32
antecedent 32
consequent 32
implication 32, 35, 37, 39, 43, 60, 63, 86
implication Seealsoif-then rules 32, 133
initfcm 121
L
logical operations 28
M
mam2sug 3-45
Mamdanis method 36
Mamdani-styleinference133
Mamdani-typeinference35, 49, 86, 90
max 41, 43
membership function 23, 28, 35, 53, 55, 118, 133
mf editor 103
Membership Function Editor 45, 47, 52
membership functions
bell 27
custom63
Gaussian 27
Pi 27
S 27
sigmoidal 27
Z27
MF Seealsomembership function
mf2mf 3-46
mfedit 3-47
min 43
model validation 94, 98
N
neuro-fuzzy inference93
newfis 72, 3-49
NOT 30, 103
O
OR 30, 37, 43, 103
P
parsrule 3-50
pimf 28, 3-51
plotfis 68, 3-52
plotmf 68, 90, 3-53
probabilistic OR 39
probor 41
psigmf 27, 3-54
Index
I-3
R
readfis 65, 73, 88, 3-55
rmmf 76, 3-56
rmvar 76, 3-57
RuleEditor 45, 56
ruleformats 3-15, 3-60
RuleViewer 45, 47, 59
ruleedit 3-59
ruleview 3-61
S
setfis 66, 76, 3-63
sffis 84, 3-65
showfis 67, 74, 76, 3-66
showrule 3-68
sigmf 27, 3-70
Simulink blocks
fuzzy controller with ruleviewer 81
Fuzzy Logic Controller 79, 83
Simulink, workingwith 78
singleton 36
sltank 79
smf 28, 3-71
stand-aloneC-code130
stand-alonefuzzy inferenceengine130
step size117
structure.field syntax 66, 73
subclust 3-72
subtractiveclustering100, 123, 128
Sugeno123
Sugeno-typeFI S SeealsoSugeno-typeinference
101
Sugeno-typeinference37, 45, 50, 86, 88, 120, 124,
133
sum41
SurfaceViewer 45, 47, 61
surfview 3-75
T
T-conorm31, 133
testingdata 94, 97
T-norm31, 133
trainingdata 95, 99, 115
trainingerror 117
trapezoidal 26
trapmf 26, 3-77
trimf 3-79
W
writefis 3-81
Z
zmf 28, 3-82

You might also like