Visualization
Programming
Fuzzy Logic Toolbox
For Use with MATLAB
®
User ’s Guide
Version 2
How to Contact The MathWorks:
5086477000 Phone
5086477001 Fax
The Mat hWor ks, Inc. Mail
24 Pr ime Par k Way
Nat ick, MA 017601500
http://www.mathworks.com Web
ftp.mathworks.com Anonymous FTP ser ver
comp.softsys.matlab Newsgr oup
support@mathworks.com Technical suppor t
suggest@mathworks.com Pr oduct enhancement suggest ions
bugs@mathworks.com Bug r epor t s
doc@mathworks.com Document at ion er r or r epor t s
subscribe@mathworks.com Subscr ibing user r egist r at ion
service@mathworks.com Or der st at us, license r enewals, passcodes
info@mathworks.com Sales, pr icing, and gener al infor mat ion
Fuzzy Logic Toolbox User’s Guide
© COPYRIGHT 1995  1999 by The Mat hWor ks, Inc.
The soft war e descr ibed in t his document is fur nished under a license agr eement . The soft war e may be used
or copied only under t he t er ms of t he license agr eement . No par t of t his manual may be phot ocopied or r epr o
duced in any for m wit hout pr ior wr it t en consent fr om The Mat hWor ks, Inc.
U.S. GOVERNMENT: If Licensee is acquir ing t he Pr ogr ams on behalf of any unit or agency of t he U.S.
Gover nment , t he following shall apply: (a) For unit s of t he Depar t ment of Defense: t he Gover nment shall
have only t he r ight s specified in t he license under which t he commer cial comput er soft war e or commer cial
soft war e document at ion was obt ained, as set for t h in subpar agr aph (a) of t he Right s in Commer cial
Comput er Soft war e or Commer cial Soft war e Document at ion Clause at DFARS 227.72023, t her efor e t he
r ight s set for t h her ein shall apply; and (b) For any ot her unit or agency: NOTICE: Not wit hst anding any
ot her lease or license agr eement t hat may per t ain t o, or accompany t he deliver y of, t he comput er soft war e
and accompanying document at ion, t he r ight s of t he Gover nment r egar ding it s use, r epr oduct ion, and disclo
sur e ar e as set for t h in Clause 52.22719 (c)(2) of t he FAR.
MATLAB, Simulink, St at eflow, Handle Gr aphics, and RealTime Wor kshop ar e r egist er ed t r ademar ks and
Tar get Language Compiler ar e t r ademar ks of The Mat hWor ks, Inc.
Ot her pr oduct or br and names ar e t r ademar ks or r egist er ed t r ademar ks of t heir r espect ive holder s.
Pr int ing Hist or y: J anuar y 1995 Fir st pr int ing
Apr il 1997 Second pr int ing
J anuar y 1998 Thir d pr int ingRevised for MATLAB 5.2
J anuar y 1999 Minor r evisions for Release 11 (Online only)
¤
PHONE
FAX
u
MAIL
INTERNET
@
Forward
The past few year s have wit nessed a r apid gr owt h in t he number and var iet y
of applicat ions of fuzzy logic. The applicat ions r ange fr om consumer pr oduct s
such as camer as, camcor der s, washing machines, and micr owave ovens t o
indust r ial pr ocess cont r ol, medical inst r ument at ion, decisionsuppor t syst ems,
and por t folio select ion.
To under st and t he r easons for t he gr owing use of fuzzy logic it is necessar y,
fir st , t o clar ify what is meant by fuzzy logic.
Fuzzy logic has t wo differ ent meanings. In a nar r ow sense, fuzzy logic is a
logical syst em, which is an ext ension of mult ivalued logic. But in a wider
sense—which is in pr edominant use t oday—fuzzy logic (FL) is almost
synonymous wit h t he t heor y of fuzzy set s, a t heor y which r elat es t o classes of
object s wit h unshar p boundar ies in which member ship is a mat t er of degr ee.
In t his per spect ive, fuzzy logic in it s nar r ow sense is a br anch of FL. What is
impor t ant t o r ecognize is t hat , even in it s nar r ow sense, t he agenda of fuzzy
logic is ver y differ ent bot h in spir it and subst ance fr om t he agendas of
t r adit ional mult ivalued logical syst ems.
In t he Fuzzy Logic Toolbox, fuzzy logic should be int er pr et ed as FL, t hat is,
fuzzy logic in it s wide sense. The basic ideas under lying FL ar e explained ver y
clear ly and insight fully in t he Int r oduct ion. What might be added is t hat t he
basic concept under lying FL is t hat of a linguist ic var iable, t hat is, a var iable
whose values ar e wor ds r at her t han number s. In effect , much of FL may be
viewed as a met hodology for comput ing wit h wor ds r at her t han number s.
Alt hough wor ds ar e inher ent ly less pr ecise t han number s, t heir use is closer t o
human int uit ion. Fur t her mor e, comput ing wit h wor ds exploit s t he t oler ance
for impr ecision and t her eby lower s t he cost of solut ion.
Anot her basic concept in FL, which plays a cent r al r ole in most of it s
applicat ions, is t hat of a fuzzy ift hen r ule or , simply, fuzzy r ule. Alt hough
r ulebased syst ems have a long hist or y of use in AI, what is missing in such
syst ems is a machiner y for dealing wit h fuzzy consequent s and/or fuzzy
ant ecedent s. In fuzzy logic, t his machiner y is pr ovided by what is called t he
calculus of fuzzy r ules. The calculus of fuzzy r ules ser ves as a basis for what
might be called t he Fuzzy Dependency and Command Language (FDCL).
Alt hough FDCL is not used explicit ly in Fuzzy Logic Toolbox, it is effect ively
one of it s pr incipal const it uent s. In t his connect ion, what is impor t ant t o
Forward
r ecognize is t hat in most of t he applicat ions of fuzzy logic, a fuzzy logic solut ion
is in r ealit y a t r anslat ion of a human solut ion int o FDCL.
What makes t he Fuzzy Logic Toolbox so power ful is t he fact t hat most of
human r easoning and concept for mat ion is linked t o t he use of fuzzy r ules. By
pr oviding a syst emat ic fr amewor k for comput ing wit h fuzzy r ules, t he Fuzzy
Logic Toolbox gr eat ly amplifies t he power of human r easoning. Fur t her
amplificat ion r esult s fr om t he use of MATLAB and gr aphical user int er faces –
ar eas in which The Mat hWor ks has unpar alleled exper t ise.
A t r end which is gr owing in visibilit y r elat es t o t he use of fuzzy logic in
combinat ion wit h neur ocomput ing and genet ic algor it hms. Mor e gener ally,
fuzzy logic, neur ocomput ing, and genet ic algor it hms may be viewed as t he
pr incipal const it uent s of what might be called soft comput ing. Unlike t he
t r adit ional, har d comput ing, soft comput ing is aimed at an accommodat ion
wit h t he per vasive impr ecision of t he r eal wor ld. The guiding pr inciple of soft
comput ing is: Exploit t he t oler ance for impr ecision, uncer t aint y, and par t ial
t r ut h t o achieve t r act abilit y, r obust ness, and low solut ion cost . In coming
year s, soft comput ing is likely t o play an incr easingly impor t ant r ole in t he
concept ion and design of syst ems whose MIQ (Machine IQ) is much higher t han
t hat of syst ems designed by convent ional met hods.
Among var ious combinat ions of met hodologies in soft comput ing, t he one which
has highest visibilit y at t his junct ur e is t hat of fuzzy logic and neur ocomput ing,
leading t o socalled neur ofuzzy syst ems. Wit hin fuzzy logic, such syst ems play
a par t icular ly impor t ant r ole in t he induct ion of r ules fr om obser vat ions. An
effect ive met hod developed by Dr . Roger J ang for t his pur pose is called ANFIS
(Adapt ive Neur oFuzzy Infer ence Syst em). This met hod is an impor t ant
component of t he Fuzzy Logic Toolbox.
The Fuzzy Logic Toolbox is highly impr essive in all r espect s. It makes fuzzy
logic an effect ive t ool for t he concept ion and design of int elligent syst ems. The
Fuzzy Logic Toolbox is easy t o mast er and convenient t o use. And last , but not
least impor t ant , it pr ovides a r eader fr iendly and upt odat e int r oduct ion t o t he
met hodology of fuzzy logic and it s wider anging applicat ions.
Lot fi A. Zadeh
Ber keley, CA
J anuar y 10, 1995
i
Contents
Before You Begi n
What Is t he Fuzzy Logic Toolbox? . . . . . . . . . . . . . . . . . . . . . . . . . 6
How t o Use This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Inst allat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Typogr aphical Convent ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1
Introducti on
What Is Fuzzy Logic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Why Use Fuzzy Logic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
When Not t o Use Fuzzy Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
What Can t he Fuzzy Logic Toolbox Do? . . . . . . . . . . . . . . . . . . . 16
An Introductory Example: Fuzzy vs. NonFuzzy . . . . . . . . . 18
The NonFuzzy Appr oach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
The Fuzzy Appr oach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Some Obser vat ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
2
Tutori al
The Bi g Pi ct ure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Foundati ons of Fuzzy Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Fuzzy Set s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Member ship Funct ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Logical Oper at ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
i i Contents
IfThen Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Fuzzy Inference Syst ems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Dinner for Two, Repr ise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
The Fuzzy Infer ence Diagr am . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Cust omizat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Bui ldi ng Syste ms wi th t he Fuzzy Logi c Toolbox . . . . . . . . . . 45
Dinner for Two, fr om t he Top . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Get t ing St ar t ed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
The FIS Edit or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
The Member ship Funct ion Edit or . . . . . . . . . . . . . . . . . . . . . . . . . 52
The Rule Edit or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
The Rule Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
The Sur face Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Impor t ing and Expor t ing fr om t he GUI Tools . . . . . . . . . . . . . . . 62
Cust omizing Your Fuzzy Syst em . . . . . . . . . . . . . . . . . . . . . . . . . 63
Worki ng from t he Command Li ne . . . . . . . . . . . . . . . . . . . . . . . 65
Syst em Display Funct ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Building a Syst em fr om Scr at ch . . . . . . . . . . . . . . . . . . . . . . . . . . 70
FIS Evaluat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
The FIS St r uct ur e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Worki ng wit h Si muli nk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
An Example: Wat er Level Cont r ol . . . . . . . . . . . . . . . . . . . . . . . . 78
Building Your Own Fuzzy Simulink Models . . . . . . . . . . . . . . . . 83
SugenoType Fuzzy Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
An Example: Two Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
anfi s and the ANFIS Edi tor GUI . . . . . . . . . . . . . . . . . . . . . . . . . 92
A Modeling Scenar io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Model Lear ning and Infer ence Thr ough ANFIS . . . . . . . . . . . . . 93
Familiar it y Br eeds Validat ion: Know Your Dat a . . . . . . . . . . . . . 94
Some Const r aint s of anfis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
The ANFIS Edit or GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
ANFIS Edit or GUI Example 1:
i i i
Checking Dat a Helps Model Validat ion . . . . . . . . . . . . . . . . . . . 98
ANFIS Edit or GUI Example 2:
Checking Dat a Doesn’t Validat e Model . . . . . . . . . . . . . . . . . . 106
anfis fr om t he Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Mor e on anfis and t he ANFIS Edit or GUI . . . . . . . . . . . . . . . . . 114
Fuzzy Clusteri ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Fuzzy CMeans Clust er ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Subt r act ive Clust er ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
St andAlone CCode Fuzzy Inference Engi ne . . . . . . . . . . . . 130
Glos sary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Re ference s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
3
Reference
GUI Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Member ship Funct ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
FIS Dat a St r uct ur e Management . . . . . . . . . . . . . . . . . . . . . . . . 33
Advanced Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Simulink Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
i v Contents
Befor e You Begin
What Is t he Fuzzy Logic Toolbox? . . . . . . . . . . . . . 2
How t o Use This Guide . . . . . . . . . . . . . . . . . 3
Inst allat ion . . . . . . . . . . . . . . . . . . . . . . 3
Typogr aphical Convent ions . . . . . . . . . . . . . . . 4
Before You Begin
6
This sect ion descr ibes how t o use t he Fuzzy Logic Toolbox. It explains how t o
use t his guide and point s you t o addit ional books for t oolbox inst allat ion
infor mat ion.
What Is the Fuzzy Logic Toolbox?
The Fuzzy Logic Toolbox is a collect ion of funct ions built on t he MATLAB
®
numer ic comput ing envir onment . It pr ovides t ools for you t o cr eat e and edit
fuzzy infer ence syst ems wit hin t he fr amewor k of MATLAB, or if you pr efer you
can int egr at e your fuzzy syst ems int o simulat ions wit h Simulink
®
, or you can
even build st andalone C pr ogr ams t hat call on fuzzy syst ems you build wit h
MATLAB. This t oolbox r elies heavily on gr aphical user int er face (GUI) t ools t o
help you accomplish your wor k, alt hough you can wor k ent ir ely fr om t he
command line if you pr efer .
The t oolbox pr ovides t hr ee cat egor ies of t ools:
•Command line funct ions
•Gr aphical, int er act ive t ools
•Simulink blocks and examples
The fir st cat egor y of t ools is made up of funct ions t hat you can call fr om t he
command line or fr om your own applicat ions. Many of t hese funct ions ar e
MATLAB Mfiles, ser ies of MATLAB st at ement s t hat implement specialized
fuzzy logic algor it hms. You can view t he MATLAB code for t hese funct ions
using t he st at ement
type function_name
You can change t he way any t oolbox funct ion wor ks by copying and r enaming
t he Mfile, t hen modifying your copy. You can also ext end t he t oolbox by adding
your own Mfiles.
Secondly, t he t oolbox pr ovides a number of int er act ive t ools t hat let you access
many of t he funct ions t hr ough a GUI. Toget her , t he GUI based t ools pr ovide
an envir onment for fuzzy infer ence syst em design, analysis, and
implement at ion.
The t hir d cat egor y of t ools is a set of blocks for use wit h t he Simulink
simulat ion soft war e. These ar e specifically designed for high speed fuzzy logic
infer ence in t he Simulink envir onment .
7
How to Use This Guide
If you are new to fuzzy logi c, begin wit h Chapt er 1, “Int r oduct ion.” This
chapt er int r oduces t he mot ivat ion behind fuzzy logic and leads you smoot hly
int o t he t ut or ial.
If you are an expe ri enced fuzzy logi c us er, you may want t o st ar t at t he
beginning of Chapt er 2, “Tut or ial,” t o make sur e you ar e comfor t able wit h t he
fuzzy logic t er minology in t he Fuzzy Logic Toolbox. If you just want an
over view of each gr aphical t ool and examples of specific fuzzy syst em t asks,
t ur n dir ect ly t o t he sect ion in Chapt er 2 ent it led, “Building Syst ems wit h t he
Fuzzy Logic Toolbox.” This sect ion does not include infor mat ion on t he
adapt ive dat a modeling applicat ion cover ed by t he t oolbox funct ion anfis. The
basic funct ionalit y of t his t ool can be found in t he sect ion in Chapt er 2 ent it led,
“anfis and t he ANFIS Edit or GUI.”
If you jus t want t o s tart as soon as poss i ble and exper iment , you can open an
example syst em r ight away by t yping
fuzzy tipper
This br ings up t he Fuzzy Infer ence Syst em (FIS) edit or for an example decision
making pr oblem t hat has t o do wit h how t o t ip in a r est aur ant .
All t oolbox user s should use Chapt er 3, “Refer ence,” for infor mat ion on specific
t ools or funct ions. Refer ence descr ipt ions include a synopsis of t he funct ion’s
synt ax, as well as a complet e explanat ion of opt ions and oper at ion. Many
r efer ence descr ipt ions also include helpful examples, a descr ipt ion of t he
funct ion’s algor it hm, and r efer ences t o addit ional r eading mat er ial. For
GUIbased t ools, t he descr ipt ions include opt ions for invoking t he t ool.
Installation
To inst all t his t oolbox on a wor kst at ion or a lar ge machine, see t he Installation
Guide for UNIX. To inst all t he t oolbox on a PC or Macint osh, see t he
Installation Guide for PC and Macintosh.
To det er mine if t he Fuzzy Logic Toolbox is alr eady inst alled on your syst em,
check for a subdir ect or y named fuzzy wit hin t he main t oolbox dir ect or y or
folder .
Before You Begin
8
Typographical Conventions
To Indicate This Guide Uses Example
Example code Monospace type
(Use Code tag.)
To assign t he value 5 t o A,
ent er
A = 5
Funct ion
names
Monospace type
(Use Code tag.)
The cos funct ion finds t he
cosine of each ar r ay
element .
Funct ion
synt ax
Monospace type for t ext
t hat must appear as
shown. (Use Code t ag.)
Monospace italics for
component s you can
r eplace wit h any var iable.
(Use Codei tal t ag.)
The magic funct ion uses
t he synt ax
M = magic(n)
Keys Boldface wit h an init ial
capit al let t er
(Use MenuBodytext t ag.)
Pr ess t he Return key.
Mat hemat ical
expr essions
Var iables in italics.
Funct ions, oper at or s, and
const ant s in st andar d
t ype. (Use
Equati onVari ables t ag.)
This vect or r epr esent s t he
polynomial
p = x
2
+ 2x + 3
MATLAB
out put
Monospace type
(Use Code tag.)
MATLAB r esponds wit h
A =
5
9
Menu names,
menu it ems,
and cont r ols
Boldface wit h an init ial
capit al let t er
(Use Me nuBodyte xt t ag.)
Choose t he File menu.
New t er ms NCS italics
(Use Body te xti tal t ag.)
An array is an or der ed
collect ion of infor mat ion.
To Indicate This Guide Uses Example
Before You Begin
10
1
Int r oduct ion
What Is Fuzzy Logic? . . . . . . . . . . . . . . . . 12
Why Use Fuzzy Logic? . . . . . . . . . . . . . . . . 15
When Not t o Use Fuzzy Logic . . . . . . . . . . . . . 16
What Can t he Fuzzy Logic Toolbox Do? . . . . . . . . . 16
An Introductory Example: Fuzzy vs. NonFuzzy . . . . 18
The NonFuzzy Appr oach . . . . . . . . . . . . . . . 19
The Fuzzy Appr oach . . . . . . . . . . . . . . . . . 113
Some Obser vat ions . . . . . . . . . . . . . . . . . . 114
1 Introduction
12
What Is Fuzzy Logic?
Fuzzy logic is all about t he r elat ive impor t ance of pr ecision: How impor t ant is
it t o be exact ly r ight when a r ough answer will do? All books on fuzzy logic
begin wit h a few good quot es on t his ver y t opic, and t his is no except ion. Her e
is what some clever people have said in t he past :
Pr ecision is not t r ut h.
—Henr i Mat isse
S ometimes the more measurable drives out the most important.
—René Dubos
Vagueness is no more to be done away with in the world of logic than friction in
mechanics.
—Char les Sander s Peir ce
I believe that nothing is unconditionally true, and hence I am opposed to every
statement of positive truth and every man who makes it.
—H. L. Mencken
S o far as the laws of mathematics refer to reality, they are not certain. And so
far as they are certain, they do not refer to reality.
—Alber t Einst ein
As complexity rises, precise statements lose meaning and meaningful statements
lose precision.
—Lot fi Zadeh
Some pear ls of folk wisdom also echo t hese t hought s:
Don’t lose sight of the forest for the trees.
Don’t be penny wise and pound foolish.
The Fuzzy Logic Toolbox for use wit h MATLAB is a t ool for solving pr oblems
wit h fuzzy logic. Fuzzy logic is a fascinat ing ar ea of r esear ch because it does a
good job of t r ading off bet ween significance and pr ecision—somet hing t hat
humans have been managing for a ver y long t ime.
Fuzzy logic somet imes appear s exot ic or int imidat ing t o t hose unfamiliar wit h
it , but once you become acquaint ed wit h it , it seems almost sur pr ising t hat no
one at t empt ed it sooner . In t his sense fuzzy logic is bot h old and new because,
What Is Fuzzy Logic?
13
alt hough t he moder n and met hodical science of fuzzy logic is st ill young, t he
concept s of fuzzy logic r each r ight down t o our bones.
Fuzzy logic is a convenient way t o map an input space t o an out put space. This
is t he st ar t ing point for ever yt hing else, and t he gr eat emphasis her e is on t he
wor d “convenient .”
What do I mean by mapping input space t o out put space? Her e ar e a few
examples: You t ell me how good your ser vice was at a r est aur ant , and I’ll t ell
you what t he t ip should be. You t ell me how hot you want t he wat er , and I’ll
adjust t he faucet valve t o t he r ight set t ing. You t ell me how far away t he
subject of your phot ogr aph is, and I’ll focus t he lens for you. You t ell me how
fast t he car is going and how har d t he mot or is wor king, and I’ll shift t he gear s
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
14
A gr aphical example of an input out put map is shown below.
It ’s all just a mat t er of mapping input s t o t he appr opr iat e out put s. Bet ween t he
input and t he out put we’ll put a black box t hat does t he wor k. What could go in
t he black box? Any number of t hings: fuzzy syst ems, linear syst ems, exper t
syst ems, neur al net wor ks, differ ent ial equat ions, int er polat ed
mult idimensional lookup t ables, or even a spir it ual advisor , just t o name a few
of t he possible opt ions. Clear ly t he list could go on and on.
Of t he dozens of ways t o make t he black box wor k, it t ur ns out t hat fuzzy is
oft en t he ver y best way. Why should t hat be? As Lot fi Zadeh, who is consider ed
t o be t he fat her of fuzzy logic, once r emar ked: “In almost ever y case you can
build t he same pr oduct wit hout fuzzy logic, but fuzzy is fast er and cheaper .”
Input Space
(all possible service
quality ratings)
Output Space
(all possible tips)
the “right” tip
for tonight
tonight's service
quality
An inputoutput map for the tipping problem:
“Given the quality of service, how much should I tip?”
Black
Box
What Is Fuzzy Logic?
15
Why Use Fuzzy Logic?
Her e is a list of gener al obser vat ions about fuzzy logic.
•Fuzzy logic is concept ually easy t o under st and.
The mat hemat ical concept s behind fuzzy r easoning ar e ver y simple. What
makes fuzzy nice is t he “nat ur alness” of it s appr oach and not it s far r eaching
complexit y.
•Fuzzy logic is flexible.
Wit h any given syst em, it ’s easy t o massage it or layer mor e funct ionalit y on
t op of it wit hout st ar t ing again fr om scr at ch.
•Fuzzy logic is t oler ant of impr ecise dat a.
Ever yt hing is impr ecise if you look closely enough, but mor e t han t hat , most
t hings ar e impr ecise even on car eful inspect ion. Fuzzy r easoning builds t his
under st anding int o t he pr ocess r at her t han t acking it ont o t he end.
•Fuzzy logic can model nonlinear funct ions of ar bit r ar y complexit y.
You can cr eat e a fuzzy syst em t o mat ch any set of input out put dat a. This
pr ocess is made par t icular ly easy by adapt ive t echniques like ANFIS
(Adapt ive Neur oFuzzy Infer ence Syst ems), which ar e available in t he Fuzzy
Logic Toolbox.
•Fuzzy logic can be built on t op of t he exper ience of exper t s.
In dir ect cont r ast t o neur al net wor ks, which t ake t r aining dat a and gener at e
opaque, impenet r able models, fuzzy logic let s you r ely on t he exper ience of
people who alr eady under st and your syst em.
•Fuzzy logic can be blended wit h convent ional cont r ol t echniques.
Fuzzy syst ems don’t necessar ily r eplace convent ional cont r ol met hods. In
many cases fuzzy syst ems augment t hem and simplify t heir implement at ion.
•Fuzzy logic is based on nat ur al language.
The basis for fuzzy logic is t he basis for human communicat ion. This
obser vat ion under pins many of t he ot her st at ement s about fuzzy logic.
The last st at ement is per haps t he most impor t ant one and deser ves mor e
discussion. Nat ur al language, t hat which is used by or dinar y people on a daily
basis, has been shaped by t housands of year s of human hist or y t o be convenient
and efficient . Sent ences wr it t en in or dinar y language r epr esent a t r iumph of
efficient communicat ion. We ar e gener ally unawar e of t his because or dinar y
language is, of cour se, somet hing we use ever y day. Since fuzzy logic is built
1 Introduction
16
at op t he st r uct ur es of qualit at ive descr ipt ion used in ever yday language, fuzzy
logic is easy t o use.
When Not to Use Fuzzy Logic
Fuzzy logic is not a cur eall. When should you not use fuzzy logic? The safest
st at ement is t he fir st one made in t his int r oduct ion: fuzzy logic is a convenient
way t o map an input space t o an out put space. If you find it ’s not convenient ,
t r y somet hing else. If a simpler solut ion alr eady exist s, use it . Fuzzy logic is t he
codificat ion of common sense—use common sense when you implement it and
you will pr obably make t he r ight decision. Many cont r oller s, for example, do a
fine job wit hout using fuzzy logic. However , if you t ake t he t ime t o become
familiar wit h fuzzy logic, you’ll see it can be a ver y power ful t ool for dealing
quickly and efficient ly wit h impr ecision and nonlinear it y.
What Can the Fuzzy Logic Toolbox Do?
The Fuzzy Logic Toolbox allows you t o do sever al t hings, but t he most
impor t ant t hing it let s you do is cr eat e and edit fuzzy infer ence syst ems. You
can cr eat e t hese syst ems using gr aphical t ools or commandline funct ions, or
you can gener at e t hem aut omat ically using eit her clust er ing or adapt ive
neur ofuzzy t echniques.
If you have access t o Simulink, you can easily t est your fuzzy syst em in a block
diagr am simulat ion envir onment .
The t oolbox also let s you r un your own st andalone C pr ogr ams dir ect ly,
wit hout t he need for Simulink. This is made possible by a st andalone Fuzzy
Infer ence Engine t hat r eads t he fuzzy syst ems saved fr om a MATLAB session.
What Is Fuzzy Logic?
17
You can cust omize t he st andalone engine t o build fuzzy infer ence int o your
own code. All pr ovided code is ANSI compliant .
Because of t he int egr at ed nat ur e of MATLAB’s envir onment , you can cr eat e
your own t ools t o cust omize t he Fuzzy Logic Toolbox or har ness it wit h anot her
t oolbox, such as t he Cont r ol Syst em, Neur al Net wor k, or Opt imizat ion Toolbox,
t o ment ion only a few of t he possibilit ies.
Fuzzy
Inference
System
Standalone
Fuzzy Engine
MATLAB
Fuzzy
Logic
Toolbox
Userwritten
Mfiles
Other toolboxes
Simulink
1 Introduction
18
An Introductory Example: Fuzzy vs. NonFuzzy
A specific example would be helpful at t his point . To illust r at e t he value of
fuzzy logic, we’ll show t wo differ ent appr oaches t o t he same pr oblem: linear
and fuzzy. Fir st we will wor k t hr ough t his pr oblem t he convent ional
(nonfuzzy) way, wr it ing MATLAB commands t hat spell out linear and
piecewiselinear r elat ions. Then we’ll t ake a quick look at t he same syst em
using fuzzy logic.
Consider t he t ipping pr oblem: what is t he “r ight ” amount t o t ip your
wait per son? Her e is a clear st at ement of t he pr oblem.
The Basi c Ti ppi ng Proble m. Given a number bet ween 0 and 10 t hat
r epr esent s t he qualit y of ser vice at a r est aur ant (wher e 10 is excellent ), what
should t he t ip be?
Cultural footnote: This pr oblem is based on t ipping as it is t ypically pr act iced
in t he Unit ed St at es. An aver age t ip for a meal in t he U.S. is 15%, t hough t he
act ual amount may var y depending on t he qualit y of t he ser vice pr ovided.
An Introductory Example: Fuzzy vs. NonFuzzy
19
The NonFuzzy Approach
Let ’s st ar t wit h t he simplest possible r elat ionship. Suppose t hat t he t ip always
equals 15% of t he t ot al bill.
tip = 0.15
This doesn’t r eally t ake int o account t he qualit y of t he ser vice, so we need t o
add a new t er m t o t he equat ion. Since ser vice is r at ed on a scale of 0 t o 10, we
might have t he t ip go linear ly fr om 5% if t he ser vice is bad t o 25% if t he ser vice
is excellent . Now our r elat ion looks like t his:
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
110
So far so good. The for mula does what we want it t o do, and it ’s pr et t y
st r aight for war d. However , we may want t he t ip t o r eflect t he qualit y of t he food
as well. This ext ension of t he pr oblem is defined as follows:
The Extended Tipping Problem. Given t wo set s of number s bet ween 0 and 10
(wher e 10 is excellent ) t hat r espect ively r epr esent t he qualit y of t he ser vice and
t he qualit y of t he food at a r est aur ant , what should t he t ip be?
Let ’s see how t he for mula will be affect ed now t hat we’ve added anot her
var iable. Suppose we t r y:
tip = 0.20/20*(service+food)+0.05;
In t his case, t he r esult s look pr et t y, but when you look at t hem closely, t hey
don’t seem quit e r ight . Suppose you want t he ser vice t o be a mor e impor t ant
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. NonFuzzy
111
fact or t han t he food qualit y. Let ’s say t hat t he ser vice will account for 80% of
t he over all t ipping “gr ade” and t he food will make up t he ot her 20%. Tr y:
servRatio=0.8;
tip=servRatio*(0.20/10*service+0.05) + ...
(1–servRatio)*(0.20/10*food+0.05);
The r esponse is st ill somehow t oo unifor mly linear . Suppose you want mor e of
a flat r esponse in t he middle, i.e., you want t o give a 15% t ip in gener al, and
will depar t fr om t his plat eau only if t he ser vice is except ionally good or bad.
This, in t ur n, means t hat t hose nice linear mappings no longer apply. We can
st ill salvage t hings by using a piecewise linear const r uct ion. Let ’s r et ur n t o t he
onedimensional pr oblem of just consider ing t he ser vice. You can st r ing
t oget her a simple condit ional st at ement using br eakpoint s like t his:
if service<3,
tip=(0.10/3)*service+0.05;
elseif service<7,
tip=0.15;
elseif service<=10,
tip=(0.10/3)*(service–7)+0.15;
end
0
5
10
0
5
10
0.05
0.1
0.15
0.2
0.25
service
food
t
i
p
1 Introduction
112
The plot looks like t his.
If we ext end t his t o t wo dimensions, wher e we t ake food int o account again,
somet hing like t his r esult s:
servRatio=0.8;
if service<3,
tip=((0.10/3)*service+0.05)*servRatio + ...
(1–servRatio)*(0.20/10*food+0.05);
elseif service<7,
tip=(0.15)*servRatio + ...
(1–servRatio)*(0.20/10*food+0.05);
else,
tip=((0.10/3)*(service–7)+0.15)*servRatio + ...
(1–servRatio)*(0.20/10*food+0.05);
end
0 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. NonFuzzy
113
Wow! The plot looks good, but t he funct ion is sur pr isingly complicat ed. It was
a lit t le t r icky t o code t his cor r ect ly, and it ’s definit ely not easy t o modify t his
code in t he fut ur e. Mor eover , it ’s even less appar ent how t he algor it hm wor ks
t o someone who didn’t wit ness t he or iginal design pr ocess.
The Fuzzy Approach
It would be nice if we could just capt ur e t he essent ials of t his pr oblem, leaving
aside all t he fact or s t hat could be ar bit r ar y. If we make a list of what r eally
mat t er s in t his pr oblem, we might end up wit h t he following r ule descr ipt ions:
1. If service is poor, then tip is cheap
2. If service is good, then tip is average
3. If service is excellent, then tip is generous
The or der in which t he r ules ar e pr esent ed her e is ar bit r ar y. It doesn’t mat t er
which r ules come fir st . If we want ed t o include t he food’s effect on t he t ip, we
might add t he following t wo r ules:
4. If food is rancid, then tip is cheap
5. If food is delicious, then tip is generous
In fact , we can combine t he t wo differ ent list s of r ules int o one t ight list of t hr ee
r ules like so:
1. If service is poor or the food is rancid, then tip is cheap
2. If service is good, then tip is average
3. If service is excellent or food is delicious, then tip is generous
These t hr ee r ules ar e t he cor e of our solut ion. And coincident ally, we’ve just
defined t he r ules for a fuzzy logic syst em. Now if we give mat hemat ical
meaning t o t he linguist ic var iables (what is an “aver age” t ip, for example?) we
would have a complet e fuzzy infer ence syst em. Of cour se, t her e’s a lot left t o t he
met hodology of fuzzy logic t hat we’r e not ment ioning r ight now, t hings like:
•How ar e t he r ules all combined?
•How do I define mat hemat ically what an “aver age” t ip is?
These ar e quest ions we pr ovide det ailed answer s t o in t he next few chapt er s.
The det ails of t he met hod don’t r eally change much fr om pr oblem t o pr oblem
— t he mechanics of fuzzy logic ar en’t t er r ibly complex. What mat t er s is what
1 Introduction
114
we’ve shown in t his pr eliminar y exposit ion: fuzzy is adapt able, simple, and
easily applied.
Her e is t he pict ur e associat ed wit h t he fuzzy syst em t hat solves t his pr oblem.
The pict ur e above was gener at ed by t he t hr ee r ules above. The mechanics of
how fuzzy infer ence wor ks is explained “The Big Pict ur e” on page 218,
“Foundat ions of Fuzzy Logic” on page 220, and in “Fuzzy Infer ence Syst ems”
on page 236. In t he “Building Syst ems wit h t he Fuzzy Logic Toolbox” on page
245, t he ent ir e t ipping pr oblem is wor ked t hr ough using t he gr aphical t ools in
t he Fuzzy Logic Toolbox.
Some Observations
Her e ar e some obser vat ions about t he example so far . We found a piecewise
linear r elat ion t hat solved t he pr oblem. It wor ked, but it was somet hing of a
nuisance t o der ive, and once we wr ot e it down as code, it wasn’t ver y easy t o
int er pr et . On t he ot her hand, t he fuzzy syst em is based on some “common
sense” st at ement s. Also, we wer e able t o add t wo mor e r ules t o t he bot t om of
t he list t hat influenced t he shape of t he over all out put wit hout needing t o undo
what had alr eady been done. In ot her wor ds, t he subsequent modificat ion was
pr et t y easy.
Mor eover , by using fuzzy logic r ules, t he maint enance of t he st r uct ur e of t he
algor it hm decouples along fair ly clean lines. The not ion of an aver age t ip might
change fr om day t o day, cit y t o cit y, count r y t o count r y, but t he under lying logic
is t he same: if t he ser vice is good, t he t ip should be aver age. You can r ecalibr at e
t he met hod quickly by simply shift ing t he fuzzy set t hat defines aver age
wit hout r ewr it ing t he fuzzy r ules.
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. NonFuzzy
115
You can do t his sor t of t hing wit h list s of piecewise linear funct ions, but t her e
is a gr eat er likelihood t hat r ecalibr at ion will not be so quick and simple.
For example, her e is t he piecewise linear t ipping pr oblem slight ly r ewr it t en t o
make it mor e gener ic. It per for ms t he same funct ion as befor e, only now t he
const ant s can be easily changed.
% Establish constants
lowTip=0.05; averTip=0.15; highTip=0.25;
tipRange=highTip–lowTip;
badService=0; okayService=3;
goodService=7; greatService=10;
serviceRange=greatService–badService;
badFood=0; greatFood=10;
foodRange=greatFood–badFood;
% If service is poor or food is rancid, tip is cheap
if service<okayService,
tip=(((averTip–lowTip)/(okayService–badService)) ...
*service+lowTip)*servRatio + ...
(1–servRatio)*(tipRange/foodRange*food+lowTip);
% If service is good, tip is average
elseif service<goodService,
tip=averTip*servRatio + (1–servRatio)* ...
(tipRange/foodRange*food+lowTip);
% If service is excellent or food is delicious, tip is generous
else,
tip=(((highTip–averTip)/ ...
(greatService–goodService))* ...
(service–goodService)+averTip)*servRatio + ...
(1–servRatio)*(tipRange/foodRange*food+lowTip);
end
Not ice t he t endency her e, as wit h all code, for cr eeping gener alit y t o r ender t he
algor it hm mor e and mor e opaque, t hr eat ening event ually t o obscur e it
complet ely. What we’r e doing her e isn’t (shouldn’t be!) t hat complicat ed. Tr ue,
we can fight t his t endency t o be obscur e by adding st ill mor e comment s, or
per haps by t r ying t o r ewr it e it in slight ly mor e selfevident ways, but t he
medium is not on our side.
1 Introduction
116
The t r uly fascinat ing t hing t o not ice is t hat if we r emove ever yt hing except for
t hr ee comment s, what r emain ar e exact ly t he fuzzy r ules we wr ot e down
befor e:
% If service is poor or food is rancid, tip is cheap
% If service is good, tip is average
% If service is excellent or food is delicious, tip is generous
If, as wit h a fuzzy syst em, t he comment is ident ical wit h t he code, t hink how
much mor e likely your code is t o have comment s! Fuzzy logic let s t he language
t hat ’s clear est t o you, high level comment s, also have meaning t o t he machine,
which is why it ’s a ver y successful t echnique for br idging t he gap bet ween
people and machines.
Or t hink of it t his way: by making t he equat ions as simple as possible (linear )
we make t hings simpler for t he machine but mor e complicat ed for us. But
r eally t he limit at ion is no longer t he comput er —it ’s our ment al model of what
t he comput er is doing. We all know t hat comput er s have t he abilit y t o make
t hings hopelessly complex; fuzzy logic is r eally about r eclaiming t he middle
gr ound and let t ing t he machine wor k wit h our pr efer ences r at her t han t he
ot her way ar ound. It ’s about t ime.
2
Tut or ial
The Bi g Pi ct ure . . . . . . . . . . . . . . . . . . 22
Foundati ons of Fuzzy Logic . . . . . . . . . . . . . 24
Fuzzy Inference Sys te ms . . . . . . . . . . . . . . 220
Buildi ng Systems wi th t he Fuzzy Logi c Toolbox . . . . 229
Worki ng from t he Command Li ne . . . . . . . . . . 249
Worki ng wi th Simuli nk . . . . . . . . . . . . . . . 262
SugenoType Fuzzy Inference . . . . . . . . . . . . 270
anfi s and the ANFIS Edi tor GUI . . . . . . . . . . . 276
Fuzzy Clusteri ng . . . . . . . . . . . . . . . . . 2104
St andAlone CCode Fuzzy Inference Engine . . . . 2114
Glos s ary . . . . . . . . . . . . . . . . . . . . . 2116
Refe re nce s . . . . . . . . . . . . . . . . . . . . 2118
2 Tutorial
218
The Big Picture
We’ll st ar t wit h a lit t le mot ivat ion for wher e we ar e headed in t his chapt er . The
point of fuzzy logic is t o map an input space t o an out put space, and t he pr imar y
mechanism for doing t his is a list of ift hen st at ement s called r ules. All r ules
ar e evaluat ed in par allel, and t he or der of t he r ules is unimpor t ant . The r ules
t hemselves ar e useful because t hey r efer t o var iables and t he adject ives t hat
descr ibe t hose var iables. Befor e we can build a syst em t hat int er pr et s r ules, we
have t o define all t he t er ms we plan on using and t he adject ives t hat descr ibe
t hem. If we want t o t alk about how hot t he wat er is, we need t o define t he r ange
t hat t he wat er ’s t emper at ur e can be expect ed t o var y over as well as what we
mean by t he wor d hot . These ar e all t hings we’ll be discussing in t he next
sever al sect ions of t he manual. The diagr am below is somet hing like a r oadmap
for t he fuzzy infer ence pr ocess. It shows t he gener al descr ipt ion of a fuzzy
syst em on t he left and a specific fuzzy syst em (t he t ipping example fr om t he
Int r oduct ion) on t he r ight .
To summar ize t he concept of fuzzy infer ence depict ed in t his figur e, fuzzy
inference is a method that interprets the values in the input vector and, based
on some set of rules, assigns values to the output vector.
This chapt er is designed t o guide you t hr ough t he fuzzy logic pr ocess st ep by
st ep by pr oviding an int r oduct ion t o t he t heor y and pr act ice of fuzzy logic. The
fir st t hr ee sect ions of t his chapt er ar e t he most impor t ant —t hey move fr om
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
219
gener al t o specific, fir st int r oducing under lying ideas and t hen discussing
implement at ion det ails specific t o t he t oolbox. These t hr ee ar eas ar e
•Foundati ons of fuzzy logi c, which is an int r oduct ion t o t he gener al
concept s. If you’r e alr eady familiar wit h fuzzy logic, you may want t o skip
t his sect ion.
•Fuzzy i nfere nce systems, which explains t he specific met hods of fuzzy
infer ence used in t he Fuzzy Logic Toolbox. Since t he field of fuzzy logic uses
many t er ms t hat do not yet have st andar d int er pr et at ions, you should
consider r eading t his sect ion just t o become familiar wit h t he fuzzy infer ence
pr ocess as it is employed her e.
•Bui ldi ng s ys te ms wi th the Fuzzy Logi c Toolbox, which goes int o det ail
about how you build and edit a fuzzy syst em using t his t oolbox. This
int r oduces t he gr aphical user int er face t ools available in t he Fuzzy Logic
Toolbox and guides you t hr ough t he const r uct ion of a complet e fuzzy
infer ence syst em fr om st ar t t o finish. If you just want t o get up t o speed as
quickly as possible, st ar t her e.
Aft er t his t her e ar e sect ions t hat t ouch on a var iet y of t opics, such as Simulink
use, aut omat ic r ule gener at ion, and demonst r at ions. But fr om t he point of view
of get t ing t o know t he t oolbox, t hese fir st t hr ee sect ions ar e t he most cr ucial.
2 Tutorial
220
Foundations of Fuzzy Logic
Everything is vague to a degree you do not realize till you have tried to make it
precise. —Ber t r and Russell
Fuzzy Sets
Fuzzy logic st ar t s wit h t he concept of a fuzzy set . A fuzzy set is a set wit hout a
cr isp, clear ly defined boundar y. It can cont ain element s wit h only a par t ial
degr ee of member ship.
To under st and what a fuzzy set is, fir st consider what is meant by what we
might call a classical set. A classical set is a cont ainer t hat wholly includes or
wholly excludes any given element . For example, t he set of days of t he week
unquest ionably includes Monday, Thur sday, and Sat ur day. It just as
unquest ionably excludes but t er , liber t y, and dor sal fins, and so on.
We call t his set a classical set because it ’s been ar ound for such a long t ime. It
was Ar ist ot le who fir st for mulat ed t he Law of t he Excluded Middle, which says
X must eit her be in set A or in set not A. Anot her ver sion r uns like t his:
Of any subject , one t hing must be eit her asser t ed or denied.
Her e is a r est at ement of t he law wit h annot at ions: “Of any subject (say
Monday), one t hing (being a day of t he week) must be eit her asser t ed or denied
(I asser t t hat Monday is a day of t he week).” This law demands t hat opposit es,
t he t wo cat egor ies A and not A, should bet ween t hem cont ain t he ent ir e
univer se. Ever yt hing falls int o eit her one gr oup or t he ot her . Ther e is no t hing
t hat is bot h a day of t he week and not a day of t he week.
Monday
Thursday
Liberty
Shoe
Polish
Dorsal
Fins
Butter
Saturday
Days of the week
Foundations of Fuzzy Logic
221
Now consider t he set of days compr ising a weekend. The diagr am below is one
at t empt at classifying t he weekend days.
Most would agr ee t hat Sat ur day and Sunday belong, but what about Fr iday?
It “feels” like a par t of t he weekend, but somehow it seems like it should be
t echnically excluded. So in t he diagr am above Fr iday t r ies it s best t o sit on t he
fence. Classical or “nor mal” set s wouldn’t t oler at e t his kind of t hing. Eit her
you’r e in or you’r e out . Human exper ience suggest s somet hing differ ent ,
t hough: fence sit t ing is a par t of life.
Of cour se we’r e on t r icky gr ound her e, because we’r e st ar t ing t o t ake individual
per cept ions and cult ur al backgr ound int o account when we define what
const it ut es t he weekend. But t his is exact ly t he point . Even t he dict ionar y is
impr ecise, defining t he weekend as “t he per iod fr om Fr iday night or Sat ur day
t o Monday mor ning.” We’r e ent er ing t he r ealm wher e shar p edged yesno logic
st ops being helpful. Fuzzy r easoning becomes valuable exact ly when we’r e
t alking about how people r eally per ceive t he concept “weekend” as opposed t o
a simpleminded classificat ion useful for account ing pur poses only. Mor e t han
anyt hing else, t he following st at ement lays t he foundat ions for fuzzy logic:
In fuzzy logic, the truth of any statement becomes a matter of degree.
Any st at ement can be fuzzy. The t ool t hat fuzzy r easoning gives is t he abilit y
t o r eply t o a yesno quest ion wit h a not quit eyesor no answer . This is t he kind
of t hing t hat humans do all t he t ime (t hink how r ar ely you get a st r aight
answer t o a seemingly simple quest ion) but it ’s a r at her new t r ick for
comput er s.
How does it wor k? Reasoning in fuzzy logic is just a mat t er of gener alizing t he
familiar yesno (Boolean) logic. If we give “t r ue” t he numer ical value of 1 and
Monday
Thursday
Liberty Shoe
Polish
Dorsal
Fins
Butter
Saturday
Sunday
Days of the weekend
Friday
2 Tutorial
222
“false” t he numer ical value of 0, we’r e saying t hat fuzzy logic also per mit s
inbet ween values like 0.2 and 0.7453. For inst ance:
Q: Is Sat ur day a weekend day?
A: 1 (yes, or t r ue)
Q: Is Tuesday a weekend day?
A: 0 (no, or false)
Q: Is Fr iday a weekend day?
A: 0.8 (for t he most par t yes, but not complet ely)
Q: Is Sunday a weekend day?
A: 0.95 (yes, but not quit e as much as Sat ur day).
Below on t he left is a plot t hat shows t he t r ut h values for “weekendness” if we
ar e for ced t o r espond wit h an absolut e yes or no r esponse. On t he r ight is a plot
t hat shows t he t r ut h value for weekendness if we ar e allowed t o r espond wit h
fuzzy inbet ween values.
Technically, t he r epr esent at ion on t he r ight is fr om t he domain of multivalued
logic (or mult ivalent logic). If I ask t he quest ion “Is X a member of set A?” t he
answer might be yes, no, or any one of a t housand int er mediat e values in
bet ween. In ot her wor ds, X might have par t ial member ship in A. Mult ivalued
logic st ands in dir ect cont r ast t o t he mor e familiar concept of t wovalued (or
bivalent yesno) logic. Twovalued logic has played a cent r al r ole in t he hist or y
of science since Ar ist ot le fir st codified it , but t he t ime has come for it t o shar e
t he st age.
To r et ur n t o our example, now consider a cont inuous scale t ime plot of
weekendness 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 twovalued membership
Friday Saturday Sunday Monday Thursday
1.0
0.0
Foundations of Fuzzy Logic
223
By making t he plot cont inuous, we’r e defining t he degr ee t o which any given
inst ant belongs in t he weekend r at her t han an ent ir e day. In t he plot on t he
left , not ice t hat at midnight on Fr iday, just as t he second hand sweeps past 12,
t he weekendness t r ut h value jumps discont inuously fr om 0 t o 1. This is one
way t o define t he weekend, and while it may be useful t o an account ant , it
doesn’t r eally connect wit h our r ealwor ld exper ience of weekendness.
The plot on t he r ight shows a smoot hly var ying cur ve t hat account s for t he fact
t hat all of Fr iday, and, t o a small degr ee, par t s of Thur sday, par t ake of t he
qualit y of weekendness and t hus deser ve par t ial member ship in t he fuzzy set
of weekend moment s. The cur ve t hat defines t he weekendness of any inst ant
in t ime is a funct ion t hat maps t he input space (t ime of t he week) t o t he out put
space (weekendness). Specifically it is known as a membership function. We’ll
discuss t his in gr eat er det ail in t he next sect ion.
As anot her example of fuzzy set s, consider t he quest ion of seasons. What
season is it r ight now? In t he nor t her n hemispher e, summer officially begins at
t he exact moment in t he ear t h’s or bit when t he Nor t h Pole is point ed most
dir ect ly t owar d t he sun. It occur s exact ly once a year , in lat e J une. Using t he
ast r onomical definit ions for t he season, we get shar p boundar ies as shown on
t he left in t he figur e on t he next page. But what we exper ience as t he seasons
var ies mor e or less cont inuously as shown on t he r ight below (in t emper at e
nor t her n hemispher e climat es).
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 twovalued membership
Friday Saturday Sunday Monday Thursday
1.0
0.0
2 Tutorial
224
Membership Functions
A membership function (MF) is a cur ve t hat defines how each point in t he input
space is mapped t o a member ship value (or degr ee of member ship) bet ween 0
and 1. The input space is somet imes r efer r ed t o as t he universe of discourse, a
fancy name for a simple concept .
One of t he most commonly used examples of a fuzzy set is t he set of t all people.
In t his case t he univer se of discour se is all pot ent ial height s, say fr om 3 feet t o
9 feet , and t he wor d “t all” would cor r espond t o a cur ve t hat defines t he degr ee
t o which any per son is t all. If t he set of t all people is given t he welldefined
(cr isp) boundar y of a classical set , we might say all people t aller t han six feet
ar e officially consider ed t all. But such a dist inct ion is clear ly absur d. It may
make sense t o consider t he set of all r eal number s gr eat er t han six because
number s belong on an abst r act plane, but when we want t o t alk about r eal
people, it is unr easonable t o call one per son shor t and anot her one t all when
t hey differ in height by t he widt h of a hair .
But if t he kind of dist inct ion shown above is unwor kable, t hen what is t he r ight
way t o define t he set of t all people? Much as wit h our plot of weekend days, t he
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
225
figur e below shows a smoot hly var ying cur ve t hat passes fr om not t all t o t all.
The out put axis is a number known as t he member ship value bet ween 0 and 1.
The cur ve is known as a member ship funct ion and is oft en given t he
designat ion of µ. This cur ve defines t he t r ansit ion fr om not t all t o t all. Bot h
people ar e t all t o some degr ee, but one is significant ly less t all t han t he ot her .
Subject ive int er pr et at ions and appr opr iat e unit s ar e built r ight int o fuzzy set s.
If I say “She’s t all,” t he member ship funct ion “t all” should alr eady t ake int o
account whet her I’m r efer r ing t o a sixyear old or a gr own woman. Similar ly,
t he unit s ar e included in t he cur ve. Cer t ainly it makes no sense t o say “Is she
t all in inches or in met er s?”
Membership Functions in the Fuzzy Logic Toolbox
The only condit ion a member ship funct ion must r eally sat isfy is t hat it must
var y bet ween 0 and 1. The funct ion it self can be an ar bit r ar y cur ve whose
height
degree of
membership, µ
definitely a tall
person (µ = 0.95)
1.0
0.0
really not very
tall at all (µ = 0.30)
sharpedged
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
226
shape we can define as a funct ion t hat suit s us fr om t he point of view of
simplicit y, convenience, speed, and efficiency.
A classical set might be expr essed as
A = {x  x > 6}
A fuzzy set is an ext ension of a classical set . If X is t he univer se of discour se
and it s element s ar e denot ed by x, t hen a fuzzy set A in X is defined as a set of
or der ed pair s:
A = {x, µ
A
(x)  x ∈ X}
µ
A
(x) is called t he member ship funct ion (or MF) of x in A. The member ship
funct ion maps each element of X t o a member ship value bet ween 0 and 1.
The Fuzzy Logic Toolbox includes 11 built in member ship funct ion t ypes.
These 11 funct ions ar e, in t ur n, built fr om sever al basic funct ions: piecewise
linear funct ions, t he Gaussian dist r ibut ion funct ion, t he sigmoid cur ve, and
quadr at ic and cubic polynomial cur ves. For det ailed infor mat ion on any of t he
member ship funct ions ment ioned below, t ur n t o Chapt er 3, “Refer ence” . By
convent ion, all member ship funct ions have t he let t er s mf at t he end of t heir
names.
The simplest member ship funct ions ar e for med using st r aight lines. Of t hese,
t he simplest is t he triangular member ship funct ion, and it has t he funct ion
name trimf. It ’s not hing mor e t han a collect ion of t hr ee point s for ming a
t r iangle. The trapezoidal member ship funct ion, trapmf, has a flat t op and
r eally is just a t r uncat ed t r iangle cur ve. These st r aight line member ship
funct ions have t he advant age of simplicit y.
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
227
Two member ship funct ions ar e built on t he Gaussian dist r ibut ion cur ve: a
simple Gaussian cur ve and a t wosided composit e of t wo differ ent Gaussian
cur ves. The t wo funct ions ar e gaussmf and gauss2mf.
The generalized bell member ship funct ion is specified by t hr ee par amet er s and
has t he funct ion name gbellmf. The bell member ship funct ion has one mor e
par amet er t han t he Gaussian member ship funct ion, so it can appr oach a
nonfuzzy set if t he fr ee par amet er is t uned. Because of t heir smoot hness and
concise not at ion, Gaussian and bell member ship funct ions ar e popular
met hods for specifying fuzzy set s. Bot h of t hese cur ves have t he advant age of
being smoot h and nonzer o at all point s.
Alt hough t he Gaussian member ship funct ions and bell member ship funct ions
achieve smoot hness, t hey ar e unable t o specify asymmet r ic member ship
funct ions, which ar e impor t ant in cer t ain applicat ions. Next we define t he
sigmoidal member ship funct ion, which is eit her open left or r ight . Asymmet r ic
and closed (i.e. not open t o t he left or r ight ) member ship funct ions can be
synt hesized using t wo sigmoidal funct ions, so in addit ion t o t he basic sigmf, we
also have t he differ ence bet ween t wo sigmoidal funct ions, dsigmf, and t he
pr oduct of t wo sigmoidal funct ions psigmf.
Polynomial based cur ves account for sever al of t he member ship funct ions in
t he t oolbox. Thr ee r elat ed member ship funct ions ar e t he Z, S , and Pi 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
228
named because of t heir shape. The funct ion zmf is t he asymmet r ical
polynomial cur ve open t o t he left , smf is t he mir r or image funct ion t hat opens
t o t he r ight , and pimf is zer o on bot h ext r emes wit h a r ise in t he middle.
Ther e’s a ver y wide select ion t o choose fr om when you’r e select ing your favor it e
member ship funct ion. And t he Fuzzy Logic Toolbox also allows you t o cr eat e
your own member ship funct ions if you find t his list t oo r est r ict ive. On t he ot her
hand, if t his list seems bewilder ing, just r emember t hat you could pr obably get
along ver y well wit h just one or t wo t ypes of member ship funct ions, for example
t he t r iangle and t r apezoid funct ions. The select ion is wide for t hose who want
t o explor e t he possibilit ies, but exot ic member ship funct ions ar e by no means
r equir ed for per fect ly good fuzzy infer ence syst ems. Finally, r emember t hat
mor e det ails ar e available on all t hese funct ions in t he r efer ence sect ion, which
makes up t he second half of t his manual.
Summary of Membership Functions
•Fuzzy set s descr ibe vague concept s (fast r unner , hot weat her , weekend
days).
•A fuzzy set admit s t he possibilit y of par t ial member ship in it . (Fr iday is sor t
of a weekend day, t he weat her is r at her hot ).
•The degr ee an object belongs t o a fuzzy set is denot ed by a member ship value
bet ween 0 and 1. (Fr iday is a weekend day t o t he degr ee 0.8).
•A member ship funct ion associat ed wit h a given fuzzy set maps an input
value t o it s appr opr iat e member ship value.
Logical Operations
We now know what ’s fuzzy about fuzzy logic, but what about t he logic?
The most impor t ant t hing t o r ealize about fuzzy logical r easoning is t he fact
t hat it is a super set of st andar d Boolean logic. In ot her wor ds, if we keep t he
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
229
fuzzy values at t heir ext r emes of 1 (complet ely t r ue), and 0 (complet ely false),
st andar d logical oper at ions will hold. As an example, consider t he st andar d
t r ut h t ables below:
Now r emember ing t hat in fuzzy logic t he t r ut h of any st at ement is a mat t er of
degr ee, how will t hese t r ut h t ables be alt er ed? The input values can be r eal
number s bet ween 0 and 1. What funct ion will pr eser ve t he r esult s of t he AND
t r ut h t able (for example) and also ext end t o all r eal number s bet ween 0 and 1?
One answer is t he min oper at ion. That is, r esolve t he st at ement A AND B,
wher e A and B ar e limit ed t o t he r ange (0,1), by using t he funct ion min(A,B).
Using t he same r easoning, we can r eplace t he OR oper at ion wit h t he max
funct ion, so t hat A OR B becomes equivalent t o max(A,B). Finally, t he
oper at ion NOT A becomes equivalent t o t he oper at ion . Not ice how t he
t r ut h t able above is complet ely unchanged by t his subst it ut ion.
Mor eover , since t her e is a funct ion behind t he t r ut h t able r at her t han just t he
t r ut h t able it self, we can now consider values ot her t han 1 and 0.
The next figur e uses a gr aph t o show t he same infor mat ion. We’ve conver t ed
t he t r ut h t able t o a plot of t wo fuzzy set s applied t oget her t o cr eat e one fuzzy
AND
0
0
1
1
A B A a nd 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 mi n(A , B) A B ma x(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
230
set . The upper par t of t he figur e displays plot s cor r esponding t o t he t wovalued
t r ut h t ables above, while t he lower par t of t he figur e displays how t he
oper at ions wor k over a cont inuously var ying r ange of t r ut h values A and B
accor ding t o t he fuzzy oper at ions we’ve defined.
Given t hese t hr ee funct ions, we can r esolve any const r uct ion using fuzzy set s
and t he fuzzy logical oper at ion AND, OR, and NOT.
Additional Fuzzy Operators
We’ve only defined her e one par t icular cor r espondence bet ween t wovalued
and mult ivalued logical oper at ions for AND, OR, and NOT. This
cor r espondence is by no means unique.
In mor e gener al t er ms, we’r e defining what ar e known as t he fuzzy int er sect ion
or conjunct ion (AND), fuzzy union or disjunct ion (OR), and fuzzy complement
(NOT). We have defined above what we’ll call t he classical oper at or s for t hese
funct ions: AND = min, OR = max, and NOT = addit ive complement . Typically
most fuzzy logic applicat ions make use of t hese oper at ions and leave it at t hat .
In gener al, however , t hese funct ions ar e ar bit r ar y t o a sur pr ising degr ee. The
Fuzzy Logic Toolbox uses t he classical oper at or for t he fuzzy complement as
shown above, but also enables you t o cust omize t he AND and OR oper at or s.
The int er sect ion of t wo fuzzy set s A and B is specified in gener al by a binar y
mapping T, which aggr egat es t wo member ship funct ions as follows:
µ
A∩B
(x) = T(µ
A
(x), µ
B
(x))
AND
A a nd B
Twovalued
logic
Multivalued
logic
A a nd 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) (1A)
Foundations of Fuzzy Logic
231
For example, t he binar y oper at or T may r epr esent t he mult iplicat ion of
. These fuzzy int er sect ion oper at or s, which ar e usually
r efer r ed t o as Tnor m (Tr iangular nor m) oper at or s, meet t he following basic
r equir ement s.
A Tnorm oper at or is a binar y mapping T( ) sat isfying:
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)
The fir st r equir ement imposes t he cor r ect gener alizat ion t o cr isp set s. The
second r equir ement implies t hat a decr ease in t he member ship values in A or
B cannot pr oduce an incr ease in t he member ship value in A int er sect ion B. The
t hir d r equir ement indicat es t hat t he oper at or is indiffer ent t o t he or der of t he
fuzzy set s t o be combined. Finally, t he four t h r equir ement allows us t o t ake t he
int er sect ion of any number of set s in any or der of pair wise gr oupings.
Like fuzzy int er sect ion, t he fuzzy union oper at or is specified in gener al by a
binar y mapping S :
µ
A∪B
(x) = S(µ
A
(x), µ
B
(x))
For example, t he binar y oper at or S can r epr esent t he addit ion of
. These fuzzy union oper at or s, which ar e oft en r efer r ed t o as
Tconor m (or S nor m) oper at or s, must sat isfy t he following basic r equir ement s.
A Tconorm (or S norm) oper at or is a binar y mapping S ( ) sat isfying:
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)
Sever al par amet er ized Tnor ms and dual Tconor ms have been pr oposed in t he
past , such as t hose of Yager [Yag80], Dubois and Pr ade [Dub80], Schweizer and
Sklar [Sch63], and Sugeno [Sug77]. Each of t hese pr ovides a way t o var y t he
“gain” on t he funct ion so t hat it can be ver y r est r ict ive or ver y per missive.
µ
A
x ( ) and µ
B
x ( )
.
,
.
µ
A
x ( ) and µ
B
x ( )
.
,
.
2 Tutorial
232
IfThen Rules
Fuzzy set s and fuzzy oper at or s ar e t he subject s and ver bs of fuzzy logic. These
ift hen r ule st at ement s ar e used t o for mulat e t he condit ional st at ement s t hat
compr ise fuzzy logic.
A single fuzzy ift hen r ule assumes t he for m
if x is A t hen y is B
wher e A and B ar e linguist ic values defined by fuzzy set s on t he r anges
(univer ses of discour se) X and Y, r espect ively. The ifpar t of t he r ule “x is A” is
called t he antecedent or pr emise, while t he t henpar t of t he r ule “y is B” is called
t he consequent or conclusion. An example of such a r ule might be
if service is good then tip is average
Not e t hat good is r epr esent ed as a number bet ween 0 and 1, and so t he
ant ecedent is an int er pr et at ion t hat r et ur ns a single number bet ween 0 and 1.
On t he ot her hand, average is r epr esent ed as a fuzzy set , and so t he consequent
is an assignment t hat assigns t he ent ir e fuzzy set B t o t he out put var iable y. In
t he ift hen r ule, t he wor d “is” get s used in t wo ent ir ely differ ent ways
depending on whet her it appear s in t he ant ecedent or t he consequent . In
MATLAB t er ms, t his is t he dist inct ion bet ween a r elat ional t est using “==” and
a var iable assignment using t he “=” symbol. A less confusing way of wr it ing t he
r ule would be
if service == good then tip = average
In gener al, t he input t o an ift hen r ule is t he cur r ent value for t he input
var iable (in t his case, service) and t he out put is an ent ir e fuzzy set (in t his case,
average). This set will lat er be defuzzified, assigning one value t o t he out put .
The concept of defuzzificat ion is descr ibed in t he next sect ion, on page 241.
Int er pr et ing an ift hen r ule involves dist inct par t s: fir st evaluat ing t he
ant ecedent (which involves fuzzifying t he input and applying any necessar y
fuzzy operators) and second applying t hat r esult t o t he consequent (known as
implication). In t he case of t wovalued or binar y logic, ift hen r ules don’t
pr esent much difficult y. If t he pr emise is t r ue, t hen t he conclusion is t r ue. If we
r elax t he r est r ict ions of t wovalued logic and let t he ant ecedent be a fuzzy
st at ement , how does t his r eflect on t he conclusion? The answer is a simple one:
Foundations of Fuzzy Logic
233
if t he ant ecedent is t r ue t o some degr ee of member ship, t hen t he consequent is
also t r ue t o t hat same degr ee. In ot her wor ds
in binar y logic: p → q (p and q ar e eit her bot h t r ue or bot h false)
in fuzzy logic: 0.5 p → 0.5 q (par t ial ant ecedent s pr ovide par t ial implicat ion)
The ant ecedent of a r ule can have mult iple par t s:
if sky is gray and wind is strong and barometer is falling, then ...
in which case all par t s of t he ant ecedent ar e calculat ed simult aneously and
r esolved t o a single number using t he logical oper at or s descr ibed in t he
pr eceding sect ion. The consequent of a r ule can also have mult iple par t s:
if temperature is cold then hot water valve is open and cold water valve is shut
in which case all consequent s ar e affect ed equally by t he r esult of t he
ant ecedent . How is t he consequent affect ed by t he ant ecedent ? The consequent
specifies a fuzzy set be assigned t o t he out put . The implication function t hen
modifies t hat fuzzy set t o t he degr ee specified by t he ant ecedent . The most
common ways t o modify t he out put fuzzy set ar e t r uncat ion using t he min
funct ion (wher e t he fuzzy set is “chopped off” as shown below) or scaling using
t he prod funct ion (wher e t he out put fuzzy set is “squashed”). Bot h ar e
suppor t ed by t he Fuzzy Logic Toolbox, but we use t r uncat ion for t he examples
in t his sect ion.
2 Tutorial
234
Summary of IfThen Rules
Int er pr et ing ift hen r ules is a t hr eepar t pr ocess. This pr ocess is explained in
det ail in t he next sect ion.
delicious
excellent
generous
If service i s excellent food i s delicious then or tip = generous
food (crisp)
tip (fuzzy)
service (crisp)
3. Apply
i mpli cati on
operator (mi n)
2. Apply
O R operator
(max)
1. Fuzzi fy
i nputs
µ
(food==deli ci ous)
= 0 .7 µ
(servi ce==excellent)
= 0 .0
mi n(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
235
1 Fuzzify inputs: Resolve all fuzzy st at ement s in t he ant ecedent t o a degr ee of
member ship bet ween 0 and 1. If t her e is only one par t t o t he ant ecedent , t his
is t he degr ee of suppor t for t he r ule.
2 Apply fuzzy operator to multiple part antecedents: If t her e ar e mult iple par t s
t o t he ant ecedent , apply fuzzy logic oper at or s and r esolve t he ant ecedent t o
a single number bet ween 0 and 1. This is t he degr ee of suppor t for t he r ule.
3 Apply implication method: Use t he degr ee of suppor t for t he ent ir e r ule t o
shape t he out put fuzzy set . The consequent of a fuzzy r ule assigns an ent ir e
fuzzy set t o t he out put . This fuzzy set is r epr esent ed by a member ship
funct ion t hat is chosen t o indicat e t he qualit ies of t he consequent . If t he
ant ecedent is only par t ially t r ue, (i.e., is assigned a value less t han 1), t hen
t he out put fuzzy set is t r uncat ed accor ding t o t he implicat ion met hod.
In gener al, one r ule by it self doesn’t do much good. What ’s needed ar e t wo or
mor e r ules t hat can play off one anot her . The out put of each r ule is a fuzzy set .
The out put fuzzy set s for each r ule ar e t hen aggregated int o a single out put
fuzzy set . Finally t he r esult ing set is defuzzified, or r esolved t o a single
number . The next sect ion shows how t he whole pr ocess wor ks fr om beginning
t o end for a par t icular t ype of fuzzy infer ence syst em called a Mamdani t ype.
2 Tutorial
236
Fuzzy Inference Systems
Fuzzy infer ence is t he pr ocess of for mulat ing t he mapping fr om a given input
t o an out put using fuzzy logic. The mapping t hen pr ovides a basis fr om which
decisions can be made, or pat t er ns discer ned. The pr ocess of fuzzy infer ence
involves all of t he pieces t hat ar e descr ibed in t he pr evious sect ions:
member ship funct ions, fuzzy logic oper at or s, and ift hen r ules. Ther e ar e t wo
t ypes of fuzzy infer ence syst ems t hat can be implement ed in t he Fuzzy Logic
Toolbox: Mamdanit ype and Sugenot ype. These t wo t ypes of infer ence syst ems
var y somewhat in t he way out put s ar e det er mined. Descr ipt ions of t hese t wo
t ypes of fuzzy infer ence syst ems can be found in t he r efer ences, [J an97,
Mam75, Sug85].
Fuzzy infer ence syst ems have been successfully applied in fields such as
aut omat ic cont r ol, dat a classificat ion, decision analysis, exper t syst ems, and
comput er vision. Because of it s mult idisciplinar y nat ur e, fuzzy infer ence
syst ems ar e associat ed wit h a number of names, such as fuzzyr ulebased
syst ems, fuzzy exper t syst ems, fuzzy modeling, fuzzy associat ive memor y,
fuzzy logic cont r oller s, and simply (and ambiguously) fuzzy syst ems. Since t he
t er ms used t o descr ibe t he var ious par t s of t he fuzzy infer ence pr ocess ar e far
fr om st andar d, we will t r y t o be as clear as possible about t he differ ent t er ms
int r oduced in t his sect ion.
Mamdani’s fuzzy infer ence met hod is t he most commonly seen fuzzy
met hodology. Mamdani’s met hod was among t he fir st cont r ol syst ems built
using fuzzy set t heor y. It was pr oposed in 1975 by Ebr ahim Mamdani [Mam75]
as an at t empt t o cont r ol a st eam engine and boiler combinat ion by synt hesizing
a set of linguist ic cont r ol r ules obt ained fr om exper ienced human oper at or s.
Mamdani’s effor t was based on Lot fi Zadeh’s 1973 paper on fuzzy algor it hms
for complex syst ems and decision pr ocesses [Zad73]. Alt hough t he infer ence
pr ocess we descr ibe in t he next few sect ions differ s somewhat fr om t he met hods
descr ibed in t he or iginal paper , t he basic idea is much t he same.
Mamdanit ype infer ence, as we have defined it for t he Fuzzy Logic Toolbox,
expect s t he out put member ship funct ions t o be fuzzy set s. Aft er t he
aggr egat ion pr ocess, t her e is a fuzzy set for each out put var iable t hat needs
defuzzificat ion. It ’s possible, and in many cases much mor e efficient , t o use a
single spike as t he out put member ship funct ion r at her t han a dist r ibut ed fuzzy
set . This is somet imes known as a singleton out put member ship funct ion, and
it can be t hought of as a pr edefuzzified fuzzy set . It enhances t he efficiency of
t he defuzzificat ion pr ocess because it gr eat ly simplifies t he comput at ion
Fuzzy Inference Systems
237
r equir ed by t he mor e gener al Mamdani met hod, which finds t he cent r oid of a
t wodimensional funct ion. Rat her t han int egr at ing acr oss t he t wodimensional
funct ion t o find t he cent r oid, we use t he weight ed aver age of a few dat a point s.
Sugenot ype syst ems suppor t t his t ype of model. In gener al, Sugenot ype
syst ems can be used t o model any infer ence syst em in which t he out put
member ship funct ions ar e eit her linear or const ant .
Dinner for Two, Reprise
In t his sect ion we pr ovide t he same t woinput oneout put t hr eer ule t ipping
pr oblem t hat you saw in t he int r oduct ion, only in mor e det ail. The basic
st r uct ur e of t his example is shown in t he diagr am below.
Infor mat ion flows fr om left t o r ight , fr om t wo input s t o a single out put . The
par allel nat ur e of t he r ules is one of t he mor e impor t ant aspect s of fuzzy logic
syst ems. Inst ead of shar p swit ching bet ween modes based on br eakpoint s, we
will glide smoot hly fr om r egions wher e t he syst em’s behavior is dominat ed by
eit her one r ule or anot her .
In t he Fuzzy Logic Toolbox, t her e ar e five par t s of t he fuzzy infer ence pr ocess:
fuzzificat ion of t he input var iables, applicat ion of t he fuzzy oper at or (AND or
OR) in t he ant ecedent , implicat ion fr om t he ant ecedent t o t he consequent ,
aggr egat ion of t he consequent s acr oss t he r ules, and defuzzificat ion. These
somet imes cr ypt ic and odd names have ver y specific meaning t hat we’ll define
car efully as we st ep t hr ough each of t hem in mor e det ail below.
Input 1
Service (010)
Output
Tip (525%)
Input 2
Food (010)
Σ
Dinner for two
a 2 input, 1 output, 3 rule system
All rules are
evaluated i n parallel
usi ng fuzzy
reasoni ng.
The results of the rules
are combi ned and
di sti lled (defuzzi fi ed).
The result i s a cri sp
(nonfuzzy) number.
The i nputs are cri sp
(nonfuzzy) numbers
li mi ted to a speci fi c
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
238
Step 1. Fuzzify Inputs
The fir st st ep is t o t ake t he input s and det er mine t he degr ee t o which t hey
belong t o each of t he appr opr iat e fuzzy set s via member ship funct ions. In t he
Fuzzy Logic Toolbox, t he input is always a cr isp numer ical value limit ed t o t he
univer se of discour se of t he input var iable (in t his case t he int er val bet ween 0
and 10) and t he out put is a fuzzy degr ee of member ship in t he qualifying
linguist ic set (always t he int er val bet ween 0 and 1). Fuzzificat ion of t he input
amount s t o eit her a t able lookup or a funct ion evaluat ion.
The example we’r e using in t his sect ion is built on t hr ee r ules, and each of t he
r ules depends on r esolving t he input s int o a number of differ ent fuzzy linguist ic
set s: ser vice is poor , ser vice is good, food is r ancid, food is delicious, and so on.
Befor e t he r ules can be evaluat ed, t he input s must be fuzzified accor ding t o
each of t hese linguist ic set s. For example, t o what ext ent is t he food r eally
delicious? The figur e below shows how well t he food at our hypot het ical
r est aur ant (r at ed on a scale of 0 t o 10) qualifies, (via it s member ship funct ion),
as t he linguist ic var iable “delicious.” In t his case, we r at ed t he food as an 8,
which, given our gr aphical definit ion of delicious, cor r esponds t o µ = 0.7 for t he
“delicious” member ship funct ion.
(The compliment t o t he chef would be “your food is delicious t o t he degr ee 0.7.”)
In t his manner , each input is fuzzified over all t he qualifying member ship
funct ions r equir ed by t he r ules.
Step 2. Apply Fuzzy Operator
Once t he input s have been fuzzified, we know t he degr ee t o which each par t of
t he ant ecedent has been sat isfied for each r ule. If t he ant ecedent of a given r ule
has mor e t han one par t , t he fuzzy oper at or is applied t o obt ain one number t hat
r epr esent s t he r esult of t he ant ecedent for t hat r ule. This number will t hen be
applied t o t he out put funct ion. The input t o t he fuzzy oper at or is t wo or mor e
delicious
0.7
food i s delicious
food = 8
input
Result of
fuzzification
1. Fuzzify
inputs.
Fuzzy Inference Systems
239
member ship values fr om fuzzified input var iables. The out put is a single t r ut h
value.
As is descr ibed in t he sect ion on fuzzy logical oper at ions, any number of
welldefined met hods can fill in for t he AND oper at ion or t he OR oper at ion. In
t he Fuzzy Logic Toolbox, t wo built in AND met hods ar e suppor t ed: min
(minimum) and prod (pr oduct ). Two built in OR met hods ar e also suppor t ed:
max (maximum), and t he pr obabilist ic OR met hod probor. The pr obabilist ic OR
met hod (also known as t he algebr aic sum) is calculat ed accor ding t o t he
equat ion
probor(a,b) = a + b  ab
In addit ion t o t hese built in met hods, you can cr eat e your own met hods for
AND and OR by wr it ing any funct ion and set t ing t hat t o be your met hod of
choice. Ther e will be mor e infor mat ion on how t o do t his lat er .
Shown below is an example of t he OR oper at or max at wor k. We’r e evaluat ing
t he ant ecedent of t he r ule 3 for t he t ipping calculat ion. The t wo differ ent pieces
of t he ant ecedent (ser vice is excellent and food is delicious) yielded t he fuzzy
member ship values 0.0 and 0.7 r espect ively. The fuzzy OR oper at or simply
select s t he maximum of t he t wo values, 0.7, and t he fuzzy oper at ion for r ule 3
is complet e. If we wer e using t he pr obabilist ic OR met hod, t he r esult would st ill
be 0.7 in t his case.
Step 3. Apply Implication Method
Befor e applying t he implicat ion met hod, we must t ake car e of t he r ule’s weight .
Ever y r ule has a weight (a number bet ween 0 and 1), which is applied t o t he
number given by t he ant ecedent . Gener ally t his weight is 1 (as it is for t his
example) and so it has no effect at all on t he implicat ion pr ocess. Fr om t ime t o
delicious
excellent
0.0 0.0
0.7
0.7
service i s excellent food i s delicious or
food = 8
input 2
result of
fuzzy operator
service = 3
input 1
2. Apply
OR operator (max).
1. Fuzzi fy
i nputs.
2 Tutorial
240
t ime you may want t o weight one r ule r elat ive t o t he ot her s by changing it s
weight value t o somet hing ot her t han 1.
Once pr oper weight ing has been assigned t o each r ule, t he implicat ion met hod
is implement ed. A consequent is a fuzzy set r epr esent ed by a member ship
funct ion, which weight s appr opr iat ely t he linguist ic char act er ist ics t hat ar e
at t r ibut ed t o it . The consequent is r eshaped using a funct ion associat ed wit h
t he ant ecedent (a single number ). The input for t he implicat ion pr ocess is a
single number given by t he ant ecedent , and t he out put is a fuzzy set .
Implicat ion is implement ed for each r ule. Two built in met hods ar e suppor t ed,
and t hey ar e t he same funct ions t hat ar e used by t he AND met hod: min
(minimum), which t r uncat es t he out put fuzzy set , and prod (pr oduct ), which
scales t he out put fuzzy set .
Step 4. Aggregate All Outputs
Since decisions ar e based on t he t est ing of all of t he r ules in an FIS, t he r ules
must be combined in some manner in or der t o make a decision. Aggr egat ion is
t he pr ocess by which t he fuzzy set s t hat r epr esent t he out put s of each r ule ar e
combined int o a single fuzzy set . Aggr egat ion only occur s once for each out put
var iable, just pr ior t o t he fift h and final st ep, defuzzificat ion. The input of t he
aggr egat ion pr ocess is t he list of t r uncat ed out put funct ions r et ur ned by t he
implicat ion pr ocess for each r ule. The out put of t he aggr egat ion pr ocess is one
fuzzy set for each out put var iable.
delicious
excellent
generous
If service i s excellent food i s delicious then or tip = generous
food = 8
input 2
result of
implication
service = 3
input 1
3. Apply
Implication
operator (min).
2. Apply
O R operator (max).
1. Fuzzi fy
i nputs.
Antecedent Consequent
Fuzzy Inference Systems
241
Not ice t hat as long as t he aggr egat ion met hod is commut at ive (which it always
should be), t hen t he or der in which t he r ules ar e execut ed is unimpor t ant .
Thr ee built in met hods ar e suppor t ed: max (maximum), probor (pr obabilist ic
or ), and sum (simply t he sum of each r ule’s out put set ).
In t he diagr am below, all t hr ee r ules have been placed t oget her t o show how
t he out put of each r ule is combined, or aggr egat ed, int o a single fuzzy set whose
member ship funct ion assigns a weight ing for ever y out put (t ip) value.
Step 5. Defuzzify
The input for t he defuzzificat ion pr ocess is a fuzzy set (t he aggr egat e out put
fuzzy set ) and t he out put is a single number . As much as fuzziness helps t he
r ule evaluat ion dur ing t he int er mediat e st eps, t he final desir ed out put for each
var iable is gener ally a single number . However , t he aggr egat e of a fuzzy set
encompasses a r ange of out put values, and so must be defuzzified in or der t o
r esolve a single out put value fr om t he set .
4. Apply
aggregation
method (max).
2. Apply
fuzzy
operati on
(O R = max).
1. Fuzzi fy i nputs.
3. Apply
i mpli cati on
method (mi n).
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 ha s
no d ep end ency
on i np ut 2
service = 3
input 1
If service i s poor food i s rancid then or tip = cheap
If service i s good then tip = average
If service i s excellent food i s delicious then or tip = generous
1.
2.
3.
2 Tutorial
242
Per haps t he most popular defuzzificat ion met hod is t he cent r oid calculat ion,
which r et ur ns t he cent er of ar ea under t he cur ve. Ther e ar e five built in
met hods suppor t ed: cent r oid, bisect or , middle of maximum (t he aver age of t he
maximum value of t he out put set ), lar gest of maximum, and smallest of
maximum.
The Fuzzy Inference Diagram
The fuzzy infer ence diagr am is t he composit e of all t he smaller diagr ams we’ve
been looking at so far in t his sect ion. It simult aneously displays all par t s of t he
fuzzy infer ence pr ocess we’ve examined. Infor mat ion flows t hr ough t he fuzzy
infer ence diagr am as shown below.
Not ice how t he flow pr oceeds up fr om t he input s in t he lower left , t hen acr oss
each r ow, or r ule, and t hen down t he r ule out put s t o finish in t he lower r ight .
This is a ver y compact way of showing ever yt hing at once, fr om linguist ic
var iable fuzzificat ion all t he way t hr ough defuzzificat ion of t he aggr egat e
out put .
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
243
Shown below is t he r eal fullsize fuzzy infer ence diagr am. Ther e’s a lot t o see
in a fuzzy infer ence diagr am, but once you become accust omed t o it , you can
lear n a lot about a syst em ver y quickly. For inst ance, fr om t his diagr am wit h
t hese par t icular input s, you can easily see t hat t he implicat ion met hod is
t r uncat ion wit h t he min funct ion. The max funct ion is being used for t he fuzzy
OR oper at ion. Rule 3 (t he bot t ommost r ow in t he diagr am shown opposit e) is
having t he st r ongest influence on t he out put . And so on. The Rule Viewer
descr ibed in “The Rule Viewer ” on page 259 is a MATLAB implement at ion of
t he fuzzy infer ence diagr am.
Customization
One of t he pr imar y goals of t he Fuzzy Logic Toolbox is t o have an open and
easily modified fuzzy infer ence syst em st r uct ur e. Thus, t he Fuzzy Logic
Toolbox is designed t o give you as much fr eedom as possible, wit hin t he basic
5. Defuzzi fy
(centroi d).
4. Apply
aggregati on
method (max).
2. Apply
fuzzy
operati on
(O R = max).
1. Fuzzi fy i nputs.
3. Apply
i mpli cati on
method (mi n).
0% 25%
0% 25%
0% 25%
0% 25%
0% 25%
delicious
average
good
excellent
rancid cheap poor
food = 8
input 2
output
rule 2 ha s
no d ep end ency
on i np ut 2
tip = 16.7%
service = 3
input 1
If service i s poor food i s rancid tip = cheap then or
If service i s good then tip = average
If service i s excellent food i s 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
244
const r aint s of t he pr ocess descr ibed her e, t o cust omize t he fuzzy infer ence
pr ocess for your applicat ion. For example, you can subst it ut e your own
MATLAB funct ions for any of t he default funct ions used in t he five st eps
det ailed above: you make your own member ship funct ions, AND met hods, OR
met hods, implicat ion met hods, aggr egat ion met hods, and defuzzificat ion
met hods. The next sect ion descr ibes exact ly how t o build and implement a
fuzzy infer ence syst em using t he t ools pr ovided.
Building Systems with the Fuzzy Logic Toolbox
245
Building Systems with the Fuzzy Logic Toolbox
Dinner for Two, from the Top
Now we’r e going t o wor k t hr ough a similar t ipping example, only we’ll be
building it using t he gr aphical user int er face (GUI) t ools pr ovided by t he Fuzzy
Logic Toolbox. Alt hough it ’s possible t o use t he Fuzzy Logic Toolbox by wor king
st r ict ly fr om t he command line, in gener al it ’s much easier t o build a syst em
gr aphically. Ther e ar e five pr imar y GUI t ools for building, edit ing, and
obser ving fuzzy infer ence syst ems in t he Fuzzy Logic Toolbox: t he Fuzzy
Infer ence Syst em or FIS Edit or , t he Member ship Funct ion Edit or , t he Rule
Edit or , t he Rule Viewer , and t he Sur face Viewer . These GUIs ar e dynamically
linked, in t hat changes you make t o t he FIS using one of t hem, can affect what
you see on any of t he ot her open GUIs. You can have any or all of t hem open for
any given syst em.
In addit ion t o t hese five pr imar y GUIs, t he t oolbox includes t he gr aphical
ANFIS Edit or GUI, which is used for building and analyzing Sugenot ype
adapt ive neur al fuzzy infer ence syst ems. The ANFIS Edit or GUI is discussed
lat er in t his chapt er , in t he sect ion, “SugenoType Fuzzy Infer ence” on page
286.
2 Tutorial
246
The FIS Edit or handles t he high level issues for t he syst em: How many input
and out put var iables? What ar e t heir names? The Fuzzy Logic Toolbox doesn’t
limit t he number of input s. However , t he number of input s may be limit ed by
t he available memor y of your machine. If t he number of input s is t oo lar ge, or
t he number of member ship funct ions is t oo big, t hen it may also be difficult t o
analyze t he FIS using t he ot her GUI t ools.
The Member ship Funct ion Edit or is used t o define t he shapes of all t he
member ship funct ions associat ed wit h each var iable.
The Rule Edit or is for edit ing t he list of r ules t hat defines t he behavior of t he
syst em.
Fuzzy
Inference
System
FIS Editor
Membership
Function Editor
Rule Editor
Rule Viewer Surface Viewer
Readonly
tools
Building Systems with the Fuzzy Logic Toolbox
247
The Rule Viewer and t he Sur face Viewer ar e used for looking at , as opposed t o
edit ing, t he FIS. They ar e st r ict ly r eadonly t ools. The Rule Viewer is a
MATLABbased display of t he fuzzy infer ence diagr am shown at t he end of t he
last sect ion. Used as a diagnost ic, it can show (for example) which r ules ar e
act ive, or how individual member ship funct ion shapes ar e influencing t he
r esult s. The Sur face Viewer is used t o display t he dependency of one of t he
out put s on any one or t wo of t he input s—t hat is, it gener at es and plot s an
out put sur face map for t he syst em.
This chapt er began wit h an illust r at ion similar t o t he one below descr ibing t he
main par t s of a fuzzy infer ence syst em, only t he one below shows how t he t hr ee
Edit or s fit t oget her . The t wo Viewer s examine t he behavior of t he ent ir e
syst em.
The five pr imar y GUIs can all int er act and exchange infor mat ion. Any one of
t hem can r ead and wr it e bot h t o t he wor kspace and t o t he disk (t he readonly
viewer s can st ill exchange plot s wit h t he wor kspace and/or t he disk). For any
fuzzy infer ence syst em, any or all of t hese five GUIs may be open. If mor e t han
one of t hese edit or s is open for a single syst em, t he var ious GUI windows ar e
awar e of t he exist ence of t he ot her s, and will, if necessar y, updat e r elat ed
windows. Thus if t he names of t he member ship funct ions ar e changed using
t he Member ship Funct ion Edit or , t hose changes ar e r eflect ed in t he r ules
shown in t he Rule Edit or . The edit or s for any number of differ ent FIS syst ems
may be open simult aneously. The FIS Edit or , t he Member ship Funct ion
Edit or , and t he Rule Edit or can all r ead and modify t he FIS dat a, but t he Rule
Viewer and t he Sur face Viewer do not modify t he FIS dat a 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
248
Getting Started
We’ll st ar t wit h a basic descr ipt ion of a t woinput , oneout put t ipping pr oblem
(based on t ipping pr act ices in t he U.S.).
The Basic Tipping Problem. Given a number bet ween 0 and 10 t hat r epr esent s t he
qualit y of ser vice at a r est aur ant (wher e 10 is excellent ), and anot her number
bet ween 0 and 10 t hat r epr esent s t he qualit y of t he food at t hat r est aur ant
(again, 10 is excellent ), what should t he t ip be?
The st ar t ing point is t o wr it e down t he t hr ee golden r ules of t ipping, based on
year s of per sonal exper ience in r est aur ant s.
1. If the service is poor or the food is rancid, then tip is cheap.
2. If the service is good, then tip is average.
3. If the service is excellent or the food is delicious, then tip is generous.
We’ll assume t hat an aver age t ip is 15%, a gener ous t ip is 25%, and a cheap t ip
is 5%. It ’s also useful t o have a vague idea of what t he t ipping funct ion should
look like.
Obviously t he number s and t he shape of t he cur ve ar e subject t o local
t r adit ions, cult ur al bias, and so on, but t he t hr ee r ules ar e pr et t y univer sal.
Now we know t he r ules, and we have an idea of what t he out put should look
like. Let ’s begin wor king wit h t he GUI t ools t o const r uct a fuzzy infer ence
syst em for t his decision pr ocess.
.25
.15
.5
Bad service or bad food Great service or great food
Building Systems with the Fuzzy Logic Toolbox
249
The FIS Editor
The following discussion walks you t hr ough building a new fuzzy infer ence
syst em fr om scr at ch. If you want t o save t ime and follow along quickly, you can
load t he alr eady built syst em by t yping
fuzzy tipper
This will load t he FIS associat ed wit h t he file tipper.fis (t he .fis is implied)
and launch t he FIS Edit or . However , if you load t he pr ebuilt syst em, you will
not be building r ules and const r uct ing member ship funct ions.
The FIS Edit or displays gener al infor mat ion about a fuzzy infer ence syst em.
Ther e’s a simple diagr am at t he t op t hat shows t he names of each input
var iable on t he left , and t hose of each out put var iable on t he r ight . The sample
member ship funct ions shown in t he boxes ar e just icons and do not depict t he
act ual shapes of t he member ship funct ions.
Below t he diagr am is t he name of t he syst em and t he t ype of infer ence used.
The default , Mamdanit ype infer ence, is what we’ve been descr ibing so far and
This status line describes the
most recent operation.
These popup 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.
Doubleclick on an input
variable icon to open the
Membership Function Editor.
Doubleclick on the system
diagram to open the
Rule Editor.
Doubleclick 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
250
what we’ll cont inue t o use for t his example. Anot her slight ly differ ent t ype of
infer ence, called Sugenot ype infer ence, is also available. This met hod is
explained in “SugenoType Fuzzy Infer ence” on page 286. Below t he name of
t he fuzzy infer ence syst em, on t he left side of t he figur e, ar e t he popup menus
t hat allow you t o modify t he var ious pieces of t he infer ence pr ocess. On t he
r ight side at t he bot t om of t he figur e is t he ar ea t hat displays t he name of eit her
an input or out put var iable, it s associat ed member ship funct ion t ype, and it s
r ange. The lat t er t wo fields ar e specified only aft er t he member ship funct ions
have been. Below t hat r egion ar e t he Help and Clos e but t ons t hat call up
online help and close t he window, r espect ively. At t he bot t om is a st at us line
t hat r elays infor mat ion about t he syst em.
To st ar t t his syst em fr om scr at ch, t ype
fuzzy
at t he MATLAB pr ompt . The gener ic unt it led FIS Edit or opens, wit h one input ,
labeled i nput1, and one out put , labeled out put1. For t his example, we will
const r uct a t woinput , one out put syst em, so go t o t he Edi t menu and select
Add i nput. A second yellow box labeled i nput2 will appear . The t wo input s we
will have in our example ar e se rvi ce and food. Our one out put is ti p. We’d like
t o change t he var iable names t o r eflect t hat , t hough.
1 Click once on t he left hand (yellow) box mar ked i nput1 (t he box will be
highlight ed in r ed).
2 In t he whit e edit field on t he r ight , change input1 t o service and pr ess
Return.
3 Click once on t he left hand (yellow) box mar ked i nput2 (t he box will be
highlight ed in r ed).
4 In t he whit e edit field on t he r ight , change input2 t o food and pr ess Return.
5 Click once on t he r ight hand (blue) box mar ked output1.
6 In t he whit e edit field on t he r ight , change output1 t o tip.
Building Systems with the Fuzzy Logic Toolbox
251
7 Fr om t he Fi le menu select Save to workspace as....
8 Ent er t he var iable name tipper and click on OK.
You will see t he diagr am updat ed t o r eflect t he new names of t he input and
out put var iables. Ther e is now a new var iable in t he wor kspace called tipper
t hat cont ains all t he infor mat ion about t his syst em. By saving t o t he wor kspace
wit h a new name, you also r ename t he ent ir e syst em. Your window will look
somet hing like t his.
Leave t he infer ence opt ions in t he lower left in t heir default posit ions for now.
You’ve ent er ed all t he infor mat ion you need for t his par t icular GUI. Next
define t he member ship funct ions associat ed wit h each of t he var iables. To do
2 Tutorial
252
t his, open t he Member ship Funct ion Edit or . You can open t he Member ship
Funct ion Edit or in one of t hr ee ways:
•Pull down t he Vi e w menu it em and select Edi t Me mbe rshi p Functi ons....
•Doubleclick on t he icon for t he out put var iable, ti p.
•Type mfedit at t he command line.
The Membership Function Editor
The Member ship Funct ion Edit or shar es some feat ur es wit h t he FIS Edit or . In
fact , all of t he five basic GUI t ools have similar menu opt ions, st at us lines, and
He lp and Close but t ons. The Member ship Funct ion Edit or is t he t ool t hat let s
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 popup 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
253
you display and edit all of t he member ship funct ions associat ed wit h all of t he
input and out put var iables for t he ent ir e fuzzy infer ence syst em.
When you open t he Member ship Funct ion Edit or t o wor k on a fuzzy infer ence
syst em t hat does not alr eady exist in t he wor kspace, t her e ar e not yet any
member ship funct ions associat ed wit h t he var iables t hat you have just defined
wit h t he FIS Edit or .
On t he upper left side of t he gr aph ar ea in t he Member ship Funct ion Edit or is
a “Var iable Palet t e” t hat let s you set t he member ship funct ions for a given
var iable.To set up your member ship funct ions associat ed wit h an input or an
out put var iable for t he FIS, select an FIS var iable in t his r egion by clicking on
it .
Next select t he Edi t pulldown menu, and choose Add MFs .... A new window
will appear , which allows you t o select bot h t he member ship funct ion t ype and
t he number of member ship funct ions associat ed wit h t he select ed var iable. In
t he lower r ight cor ner of t he window ar e t he cont r ols t hat let you change t he
name, t ype, and par amet er s (shape), of t he member ship funct ion, once it has
been select ed.
The member ship funct ions fr om t he cur r ent var iable ar e displayed in t he main
gr aph. These member ship funct ions can be manipulat ed in t wo ways. You can
fir st use t he mouse t o select a par t icular member ship funct ion associat ed wit h
a given var iable qualit y, (such as poor , for t he var iable, ser vice), and t hen dr ag
t he member ship funct ion fr om side t o side. This will affect t he mat hemat ical
descr ipt ion of t he qualit y associat ed wit h t hat member ship funct ion for a given
var iable. The select ed member ship funct ion can also be t agged for dilat ion or
cont r act ion by clicking on t he small squar e dr ag point s on t he member ship
funct ion, and t hen dr agging t he funct ion wit h t he mouse t owar d t he outside,
for dilat ion, or t owar d t he inside, for cont r act ion. This will change t he
par amet er s associat ed wit h t hat member ship funct ion.
Below t he Var iable Palet t e is some infor mat ion about t he t ype and name of t he
cur r ent var iable. Ther e is a t ext field in t his r egion t hat let s you change t he
limit s of t he cur r ent var iable’s r ange (univer se of discour se) and anot her t hat
let s you set t he limit s of t he cur r ent plot (which has no r eal effect on t he
syst em).
The pr ocess of specifying t he input member ship funct ions for t his t wo input
t ipper pr oblem is as follows:
2 Tutorial
254
1 Select t he input var iable, s ervi ce, by doubleclicking on it . Set bot h t he
Range and t he Di splay Range t o t he vect or [0 10].
2 Select Add MFs... fr om t he Edi t menu. The window below pops open.
3 Use t he pulldown t ab t o choose gauss mf for MF Type and 3 for Number of
MFs. This adds t hr ee Gaussian cur ves t o t he input var iable ser vice
4 Click once on t he cur ve wit h t he left most hump. Change t he name of t he
cur ve t o poor. To adjust t he shape of t he member ship funct ion, eit her use
t he mouse, as descr ibed above, or t ype in a desir ed par amet er change, and
t hen click on t he member ship funct ion. The default par amet er list ing for
t his cur ve is [1.5 0].
5 Name t he cur ve wit h t he middle hump, good, and t he cur ve wit h t he
r ight most hump, excellent. Reset t he associat ed par amet er s if desir ed.
6 Select t he input var iable, food, by clicking on it . Set bot h t he Range and t he
Di splay Range t o t he vect or [0 10].
7 Select Add MFs... fr om t he Edi t menu and add t wo trapmf cur ves t o t he
input var iable food.
8 Click once dir ect ly on t he cur ve wit h t he left most t r apazoid. Change t he
name of t he cur ve t o rancid. To adjust t he shape of t he member ship
funct ion, eit her use t he mouse, as descr ibed above, or t ype in a desir ed
par amet er change, and t hen click on t he member ship funct ion. The default
par amet er list ing for t his cur ve is [0 0 1 3].
9 Name t he cur ve wit h t he r ight most t r apazoid, delicious, and r eset t he
associat ed par amet er s if desir ed
Building Systems with the Fuzzy Logic Toolbox
255
Next you need t o cr eat e t he member ship funct ions for t he out put var iable, ti p.
To cr eat e t he out put var iable member ship funct ions, use t he Var iable Palet t e
on t he left , select ing t he out put var iable, ti p. The input s r anged fr om 0 t o 10,
but t he out put scale is going t o be a t ip bet ween 5 and 25 per cent .
Use t r iangular member ship funct ion t ypes for t he out put . Fir st , set t he Range
(and t he Di splay Range ) t o [0 30], t o cover t he out put r ange. Init ially, t he
cheap member ship funct ion will have t he par amet er s [0 5 10], t he average
member ship funct ion will be [10 15 20], and t he generous member ship
funct ion will be [20 25 30]. Your syst em should look somet hing like t his.
Now t hat t he var iables have been named, and t he member ship funct ions have
appr opr iat e shapes and names, you’r e r eady t o wr it e down t he r ules. To call up
t he Rule Edit or , go t o t he Vi ew menu and select Edi t rules ..., or t ype ruleedit
at t he command line.
2 Tutorial
256
The Rule Editor
Const r uct ing r ules using t he gr aphical Rule Edit or int er face is fair ly
selfevident . Based on t he descr ipt ions of t he input and out put var iables
defined wit h t he FIS Edit or , t he Rule Edit or allows you t o const r uct t he r ule
st at ement s aut omat ically, by clicking on and select ing one it em in each input
var iable box, one it em in each out put box, and one connect ion it em. Choosing
none as one of t he var iable qualit ies will exclude t hat var iable fr om a given
r ule. Choosing not under any var iable name will negat e t he associat ed qualit y.
Rules may be changed, delet ed, or added, by clicking on t he appr opr iat e but t on.
The Rule Edit or also has some familiar landmar ks, similar t o t hose in t he FIS
Edit or and t he Member ship Funct ion Edit or , including t he menu bar and t he
st at us line. The Format popup menu is available fr om t he Opti ons pulldown
menu fr om t he t op menu bar —t his is used t o set t he for mat for t he display.
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
257
Similar ly, Language can be set fr om under Opti ons as well. The He lp but t on
will br ing up a MATLAB Help window.
To inser t t he fir st r ule in t he Rule Edit or , select t he following:
•poor under t he var iable s ervi ce
•ranci d under t he var iable food
•t he r adio but t on, or, in t he Connecti on block
•che ap, under t he out put var iable, ti p.
The r esult ing r ule is:
1. If (service is poor) or (food is rancid) then (tip is cheap) (1)
The number s in t he par ent heses r epr esent weight s t hat can be applied t o each
r ule if desir ed. You can specify t he weight s by t yping in a desir ed number
bet ween zer o and one under t he We i ght: set t ing. If you do not specify t hem, t he
weight s ar e assumed t o be unit y (1).
Follow a similar pr ocedur e t o inser t t he second and t hir d r ules in t he Rule
Edit or t o get :
1. If (service is poor) or (food is rancid) then (tip is cheap) (1)
2. If (service is good) then (tip is average) (1)
3. If (service is excellent) or (food is delicious) then (tip is generous) (1)
To change a r ule, fir st click on t he r ule t o be changed. Next make t he desir ed
changes t o t hat r ule, and t hen click on Change rule . For example, t o change
t he fir st r ule t o
1. If (service not poor) or (food not rancid) then (tip is not cheap) (1)
click not under each var iable, and t hen click Change rule.
The Format popup menu fr om t he Opti ons menu indicat es t hat you’r e looking
at t he ver bose for m of t he r ules. Tr y changing it t o symboli c. You will see
1. (service==poor) => (tip=cheap) (1)
2. (service==good) => (tip=average) (1)
3. (service==excellent) => (tip=generous) (1)
2 Tutorial
258
Ther e is not much differ ence in t he display r eally, but it ’s slight ly mor e
language neut r al, since it doesn’t depend on t er ms like “if” and “t hen.” If you
change t he for mat t o indexed, you’ll see an ext r emely compr essed ver sion of t he
r ules t hat has squeezed all t he language out .
1, 1 (1) : 1
2, 2 (1) : 1
3, 3 (1) : 1
This is t he ver sion t hat t he machine deals wit h. The fir st column in t his
st r uct ur e cor r esponds t o t he input var iable, t he second column cor r esponds t o
t he out put var iable, t he t hir d column displays t he weight applied t o each r ule,
and t he four t h column is shor t hand t hat indicat es whet her t his is an OR (2)
r ule or an AND (1) r ule. The number s in t he fir st t wo columns r efer t o t he index
number of t he member ship funct ion. A lit er al int er pr et at ion of r ule 1 is: “if
input 1 is MF1 (t he fir st member ship funct ion associat ed wit h input 1) t hen
out put 1 should be MF1 (t he fir st member ship funct ion associat ed wit h out put
1) wit h t he weight 1.” Since t her e is only one input for t his syst em, t he AND
connect ive implied by t he 1 in t he last column is of no consequence.
The symbolic for mat doesn’t bot her wit h t he t er ms, if, then, and so on. The
indexed for mat doesn’t even bot her wit h t he names of your var iables.
Obviously t he funct ionalit y of your syst em doesn’t depend on how well you
have named your var iables and member ship funct ions. The whole point of
naming var iables descr ipt ively is, as always, making t he syst em easier for you
t o int er pr et . Thus, unless you have some special pur pose in mind, it will
pr obably be easier for you t o st ick wit h t he ve rbos e for mat .
At t his point , t he fuzzy infer ence syst em has been complet ely defined, in t hat
t he var iables, member ship funct ions, and t he r ules necessar y t o calculat e t ips
ar e in place. It would be nice, at t his point , t o look at a fuzzy infer ence diagr am
like t he one pr esent ed at t he end of t he pr evious sect ion and ver ify t hat
ever yt hing is behaving t he way we t hink it should. This is exact ly t he pur pose
of t he Rule Viewer , t he next of t he GUI t ools we’ll look at . Fr om t he Vi e w menu,
select Vi e w rules ....
Building Systems with the Fuzzy Logic Toolbox
259
The Rule Viewer
The Rule Viewer displays a r oadmap of t he whole fuzzy infer ence pr ocess. It ’s
based on t he fuzzy infer ence diagr am descr ibed in t he pr evious sect ion. You see
a single figur e window wit h 10 small plot s nest ed in it . The t hr ee small plot s
acr oss t he t op of t he figur e r epr esent t he ant ecedent and consequent of t he fir st
r ule. Each r ule is a r ow of plot s, and each column is a var iable. The fir st t wo
columns of plot s (t he six yellow plot s) show t he member ship funct ions
r efer enced by t he ant ecedent , or t he ifpar t of each r ule. The t hir d column of
plot s (t he t hr ee blue plot s) shows t he member ship funct ions r efer enced by t he
consequent , or t he t henpar t of each r ule. If you click once on a r ule number ,
t he cor r esponding r ule will be displayed at t he bot t om of t he figur e. Not ice t hat
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 bottomright 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
260
under food, t her e is a plot which is blank. This cor r esponds t o t he
char act er izat ion of none for t he var iable food in t he second r ule. The four t h
plot in t he t hir d column of plot s r epr esent s t he aggr egat e weight ed decision for
t he given infer ence syst em. This decision will depend on t he input values for
t he syst em.
Ther e ar e also t he now familiar it ems like t he st at us line and t he menu bar . In
t he lower r ight t her e is a t ext field int o which you can ent er specific input
values. For t he t woinput syst em, you will ent er an input vect or , [9 8], for
example, and t hen click on i nput. You can also adjust t hese input values by
clicking anywher e on any of t he t hr ee plot s for each input . This will move t he
r ed index line hor izont ally, t o t he point wher e you have clicked. You can also
just click and dr ag t his line in or der t o change t he input values. When you
r elease t he line, (or aft er manually specifying t he input ), a new calculat ion is
per for med, and you can see t he whole fuzzy infer ence pr ocess t ake place.
Wher e t he index line r epr esent ing ser vice cr osses t he member ship funct ion
line “ser vice is poor ” in t he upper left plot will det er mine t he degr ee t o which
r ule one is act ivat ed. A yellow pat ch of color under t he act ual member ship
funct ion cur ve is used t o make t he fuzzy member ship value visually appar ent .
Each of t he char act er izat ions of each of t he var iables is specified wit h r espect
t o t he input index line in t his manner . If we follow r ule 1 acr oss t he t op of t he
diagr am, we can see t he consequent “t ip is cheap” has been t r uncat ed t o exact ly
t he same degr ee as t he (composit e) ant ecedent —t his is t he implicat ion pr ocess
in act ion. The aggr egat ion occur s down t he t hir d column, and t he r esult ant
aggr egat e plot is shown in t he single plot t o be found in t he lower r ight cor ner
of t he plot field. The defuzzified out put value is shown by t he t hick line passing
t hr ough t he aggr egat e fuzzy set .
The Rule Viewer allows you t o int er pr et t he ent ir e fuzzy infer ence pr ocess at
once. The Rule Viewer also shows how t he shape of cer t ain member ship
funct ions influences t he over all r esult . Since it plot s ever y par t of ever y r ule, it
can become unwieldy for par t icular ly lar ge syst ems, but , for a r elat ively small
number of input s and out put s, it per for ms well (depending on how much scr een
space you devot e t o it ) wit h up t o 30 r ules and as many as 6 or 7 var iables.
The Rule Viewer shows one calculat ion at a t ime and in gr eat det ail. In t his
sense, it pr esent s a sor t of micr o view of t he fuzzy infer ence syst em. If you want
t o see t he ent ir e out put sur face of your syst em, t hat is, t he ent ir e span of t he
out put set based on t he ent ir e span of t he input set , you need t o open up t he
Sur face Viewer . This is t he last of our five basic GUI t ools in t he Fuzzy Logic
Toolbox, and you open it by select ing Vi ew s urface ... fr om t he Vi ew menu.
Building Systems with the Fuzzy Logic Toolbox
261
The Surface Viewer
Upon opening t he Sur face Viewer , we ar e pr esent ed wit h a t wodimensional
cur ve t hat r epr esent s t he mapping fr om ser vice qualit y t o t ip amount . Since
t his is a oneinput oneout put case, we can see t he ent ir e mapping in one plot .
Twoinput oneout put syst ems also wor k well, as t hey gener at e
t hr eedimensional plot s t hat MATLAB can adept ly manage. When we move
beyond t hr ee dimensions over all, we st ar t t o encount er t r ouble displaying t he
r esult s. Accor dingly, t he Sur face Viewer is equipped wit h popup menus t hat
let you select any t wo input s and any one out put for plot t ing. J ust below t he
popup menus ar e t wo t ext input fields t hat let you det er mine how many xaxis
and yaxis gr id lines you want t o include. This allows you t o keep t he
calculat ion t ime r easonable for complex pr oblems. Pushing t he Evaluate
but t on init iat es t he calculat ion, and t he plot comes up soon aft er t he
calculat ion is complet e. To change t he xaxis or yaxis gr id aft er t he sur face is
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 popup 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 popup menu lets
you specify the
displayed output
variable.
Push this button when
you’re 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
262
in view, simply change t he appr opr iat e t ext field, and click on eit her Xgri ds :
or Ygri ds :, accor ding t o which t ext field you changed, t o r edr aw t he plot .
The Sur face Viewer has a special capabilit y t hat is ver y helpful in cases wit h
t wo (or mor e) input s and one out put : you can act ually gr ab t he axes and
r eposit ion t hem t o get a differ ent t hr eedimensional view on t he dat a. The Re f.
Input: field is used in sit uat ions when t her e ar e mor e input s r equir ed by t he
syst em t han t he sur face is mapping. Suppose you have a four input oneout put
syst em and would like t o see t he out put sur face. The Sur face Viewer can
gener at e a t hr eedimensional out put sur face wher e any t wo of t he input s var y,
but t wo of t he input s must be held const ant since comput er monit or s cannot
display a fivedimensional shape. In such a case t he input would be a
four dimensional vect or wit h NaNs holding t he place of t he var ying input s while
numer ical values would indicat e t hose values t hat r emain fixed. An NaN is t he
IEEE symbol for “not a number .”
This concludes t he quick walkt hr ough of each of t he main GUI t ools. Not ice
t hat for t he t ipping pr oblem, t he out put of t he fuzzy syst em mat ches our
or iginal idea of t he shape of t he fuzzy mapping fr om ser vice t o t ip fair ly well.
In hindsight , you might say, “Why bot her ? I could have just dr awn a quick
lookup t able and been done an hour ago!” However , if you ar e int er est ed in
solving an ent ir e class of similar decisionmaking pr oblems, fuzzy logic may
pr ovide an appr opr iat e t ool for t he solut ion, given it s ease wit h which a syst em
can be quickly modified.
Importing and Exporting from the GUI Tools
When you save a fuzzy syst em t o disk, you’r e saving an ASCII t ext FIS file
r epr esent at ion of t hat syst em wit h t he file suffix .fis. This t ext file can be
edit ed and modified and is simple t o under st and. When you save your fuzzy
syst em t o t he MATLAB wor kspace, you’r e cr eat ing a var iable (whose name you
choose) t hat will act as a MATLAB st r uct ur e for t he FIS syst em. FIS files and
FIS st r uct ur es r epr esent t he same syst em.
Note: If you do not save your FIS t o your disk, but only save it t o t he
MATLAB wor kspace, you will not be able t o r ecover it for use in a new
MATLAB session.
Building Systems with the Fuzzy Logic Toolbox
263
Customizing Your Fuzzy System
If you want t o include cust omized funct ions as par t of your use of t he Fuzzy
Logic Toolbox, t her e ar e a few guidelines you need t o follow. The AND met hod,
OR met hod, aggr egat ion met hod, and defuzzificat ion met hod funct ions you
pr ovide need t o wor k in a similar way t o max, min, or prod in MATLAB. That is,
t hey must be able t o oper at e down t he columns of a mat r ix. For example, t he
implicat ion met hod does an element by element mat r ix oper at ion, similar t o
t he min funct ion, 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 cr eat e your own member ship funct ions using an Mfile. The values
t hese funct ions can t ake must be bet ween 0 and 1. Ther e is a limit at ion on
cust omized member ship funct ions in t hat t hey cannot use mor e t han 16
par amet er s.
To define a cust om member ship funct ion named custmf:
1 Cr eat e an Mfile for a funct ion, custmf.m, t hat t akes values bet ween 0 and
1, and depends on at most 16 par amet er s.
2 Choose t he Add Cus tom MF it em in t he Edi t menu on t he Member ship
Funct ion Edit or GUI.
3 Ent er your cust om member ship funct ion Mfile name, custmf, in t he Mfi le
functi on name t ext box.
4 Ent er t he vect or of par amet er s you want t o use t o par amet er ize your
cust omized member ship funct ion in t he t ext box next t o Parameter li s t.
5 Give t he cust om member ship funct ion a name differ ent fr om any ot her
member ship funct ion name you will use in your FIS.
6 Select OK.
2 Tutorial
264
Her e is some sample code for a cust om member ship funct ion, testmf1, t hat
depends on eight par amet er s bet ween 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 t r y naming t his file testmf1.m and loading it int o t he Member ship
Funct ion Edit or using t he par amet er s of your choice.
Working from the Command Line
265
Working from the Command Line
The t ipping example syst em is one of many example fuzzy infer ence syst ems
pr ovided wit h t he Fuzzy Logic Toolbox. The FIS is always cast as a MATLAB
st r uct ur e. To load t his syst em (r at her t han bot her ing wit h cr eat ing it fr om
scr at ch), t ype
a = readfis('tipper.fis')
MATLAB will r espond wit h
a =
name: 'tipper'
type: 'mamdani'
andMethod: 'min'
orMethod: 'max'
defuzzMethod: 'centroid'
impMethod: 'min'
aggMethod: 'max'
input: [1x2 struct]
output: [1x1 struct]
rule: [1x3 struct]
The labels on t he left of t his list ing r epr esent t he var ious component s of t he
MATLAB st r uct ur e associat ed wit h tipper.fis. You can access t he var ious
component s of t his st r uct ur e by t yping t he component name aft er t yping a. At
t he MATLAB command line, t ype
a.type
for example. MATLAB will r espond wit h
ans =
mamdani
The funct ion
getfis(a)
r et ur ns almost t he same st r uct ur e infor mat ion t hat t yping a, alone does.
getfis(a) r et ur ns
Name = tipper
Type = mamdani
2 Tutorial
266
NumInputs = 2
InLabels =
service
food
NumOutputs = 1
OutLabels =
tip
NumRules = 3
AndMethod = min
OrMethod = max
ImpMethod = min
AggMethod = max
DefuzzMethod = centroid
Not ice t hat some of t hese fields ar e not par t of t he st r uct ur e, a. Thus, you
cannot get infor mat ion by t yping a.Inlabels, but you can get it by t yping:
getfis(a,'Inlabels')
Similar ly, you can obt ain st r uct ur e infor mat ion using getfis in t his manner .
getfis(a,'input',1)
getfis(a,'output',1)
getfis(a,'input',1,'mf',1)
The structure.field synt ax also gener at es t his infor mat ion. For mor e
infor mat ion on t he synt ax for MATLAB st r uct ur es, see Chapt er 13, “St r uct ur es
and Cell Ar r ays,” in Using MATLAB.
For example, t ype
a.input
or
a.input(1).mf(1)
The funct ion getfis is loosely modeled on t he Handle Gr aphics
®
funct ion get.
Ther e is also a funct ion called setfis t hat act s as t he r ecipr ocal t o getfis. It
allows you t o change any pr oper t y of an FIS. For example, if you want ed t o
change t he name of t his syst em, you could t ype
a = setfis(a,'name','gratuity');
Working from the Command Line
267
However , since a is alr eady a MATLAB st r uct ur e, you can set t his infor mat ion
mor e simply by t yping
a.name = 'gratuity';
Now t he FIS st r uct ur e a has been changed t o r eflect t he new name. If you want
a lit t le mor e insight int o t his FIS st r uct ur e, t r y
showfis(a)
This r et ur ns a pr int out list ing all t he infor mat ion about a. This funct ion is
int ended mor e for debugging t han anyt hing else, but it shows all t he
infor mat ion r ecor ded in t he FIS st r uct ur e
Since t he var iable, a, designat es t he fuzzy t ipping syst em, you can call up any
of t he GUIs for t he t ipping syst em dir ect ly fr om t he command line. Any of t he
following will br ing up t he t ipping syst em wit h t he associat ed GUI.
•fuzzy(a): br ings up t he FIS Edit or
•mfedit(a): br ings up t he Member ship Funct ion Edit or
•ruleedit(a): br ings up t he Rule Edit or
•ruleview(a): br ings up the Rule Viewer
•surfview(a): br ings up the Sur face Viewer
If, in addit ion, a is a Sugenot ype FIS, t hen anfisedit(a) will br ing up t he
ANFIS Edit or GUI.
Once any of t hese GUIs has been opened, you can access any of t he ot her GUIs
using t he pulldown menu r at her t han t he command line.
System Display Functions
Ther e ar e t hr ee funct ions designed t o give you a highlevel view of your fuzzy
infer ence syst em fr om t he command line: plotfis, plotmf, and gensurf. The
2 Tutorial
268
fir st of t hese displays t he whole syst em as a block diagr am much as it would
appear on t he FIS Edit or .
plotfis(a)
Aft er closing any open MATLAB figur es or GUI windows, t he funct ion plotmf
plot s all t he member ship funct ions associat ed wit h a given var iable as follows:
plotmf(a,'input',1)
r et ur ns
Working from the Command Line
269
plotmf(a,'output',1)
These plot s will appear in t he Member ship Funct ion Edit or GUI, or in an open
MATLAB figur e, if plotmf is called while eit her of t hese is 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
270
Finally, t he funct ion gensurf will plot any one or t wo input s ver sus any one
out put of a given syst em. The r esult is eit her a t wodimensional cur ve, or a
t hr eedimensional sur face. Not e t hat when t her e ar e t hr ee or mor e input s,
gensurf must be gener at ed wit h all but t wo input s fixed, as is descr ibed in t he
descr ipt ion of genfis in Chapt er 3, “Refer ence” .
gensurf(a)
Building a System from Scratch
It is possible t o use t he Fuzzy Logic Toolbox wit hout bot her ing wit h t he GUI
t ools at all. For inst ance, t o build t he t ipping syst em ent ir ely fr om t he
command line, you would use t he commands newfis, addvar, addmf, and
addrule.
Pr obably t he t r ickiest par t of t his pr ocess is lear ning t he shor t hand t hat t he
fuzzy infer ence syst ems use for building r ules. This is accomplished using t he
command line funct ion, addrule.
Each var iable, input , or out put , has an index number , and each member ship
funct ion has an index number . The r ules ar e built fr om st at ement s like t his
if input 1 is MF1 or input 2 is MF3 t hen out put 1 is MF2 (weight = 0.5)
This r ule is t ur ned int o a st r uct ur e accor ding t o t he following logic: If t her e ar e
m input s t o a syst em and n out put s, t hen t he fir st m vect or ent r ies of t he r ule
st r uct ur e cor r espond t o input s 1 t hr ough m. The ent r y in column 1 is t he index
number for t he member ship funct ion associat ed wit h input 1. The ent r y 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
271
column 2 is t he index number for t he member ship funct ion associat ed wit h
input 2. And so on. The next n columns wor k t he same way for t he out put s.
Column m + n + 1 is t he weight associat ed wit h t hat r ule (t ypically 1) and
column m + n + 2 specifies t he connect ive used (wher e AND = 1 and OR = 2).
The st r uct ur e associat ed wit h t he r ule shown above is
1 3 2 0.5 2
Her e is one way you can build t he ent ir e t ipping syst em fr om t he command
line, using t he MATLAB st r uct ur e synt ax.
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
272
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
Alt er nat ively, her e is how you can build t he ent ir e t ipping syst em fr om t he
command line using Fuzzy 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
273
FIS Evaluation
To evaluat e t he out put of a fuzzy syst em for a given input , use t he funct ion
evalfis. For example, t he following scr ipt evaluat es tipper at t he input , [1 2].
a = readfis('tipper');
evalfis([1 2], a)
ans =
5.5586
This funct ion can also be used for mult iple collect ions of input s, since differ ent
input vect or s ar e r epr esent ed in differ ent par t s of t he input st r uct ur e. By doing
mult iple evaluat ions at once, you get a t r emendous boost in speed.
evalfis([3 5; 2 7], a)
ans =
12.2184
7.7885
The FIS Structure
The FIS st r uct ur e is t he MATLAB object t hat cont ains all t he fuzzy infer ence
syst em infor mat ion. This st r uct ur e is st or ed inside each GUI t ool. Access
funct ions such as getfis and setfis make it easy t o examine t his st r uct ur e.
You can also access t he FIS st r uct ur e infor mat ion using t he structure.field
synt ax (see t he sect ion, “Wor king fr om t he Command Line” on page 265).
All t he infor mat ion for a given fuzzy infer ence syst em is cont ained in t he FIS
st r uct ur e, including var iable names, member ship funct ion definit ions, and so
2 Tutorial
274
on. This st r uct ur e can it self be t hought of as a hier ar chy of st r uct ur es, as shown
in t he diagr am below:
You can gener at e a list ing of infor mat ion on t he FIS using t he showfis
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
i nput
name
range
mf
rule s
antecedent
consequent
weight
connections
i nput1 MFs
name
type
params
out put MFs
name
type
params
output
name
range
mf
i nput2 MFs
name
type
params
Working from the Command Line
275
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
276
The list of command line funct ions associat ed wit h FIS const r uct ion include
getfis, setfis, showfis, addvar, addmf, addrule, rmvar, and rmmf.
Saving FIS Files on Disk
A specialized t ext file for mat is used for saving fuzzy infer ence syst ems t o a
disk. The funct ions readfis and writefis ar e used for r eading and wr it ing
t hese files.
If you pr efer , you can modify t he FIS by edit ing it s .fis t ext file r at her t han
using any of t he GUIs. You should be awar e, however , t hat changing one ent r y
may oblige you t o change anot her . For example, if you delet e a member ship
funct ion using t his met hod, you also need t o make cer t ain t hat any r ules
r equir ing t his member ship funct ion ar e also delet ed.
The r ules appear in “indexed” for mat in a .fis t ext file. Her e is t he file
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
277
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
278
Working with Simulink
The Fuzzy Logic Toolbox is designed t o wor k seamlessly wit h Simulink, t he
simulat ion soft war e available fr om The Mat hWor ks. Once you’ve cr eat ed your
fuzzy syst em using t he GUI t ools or some ot her met hod, you’r e r eady t o embed
your syst em dir ect ly int o a simulat ion.
An Example: Water Level Control
Pict ur e a t ank wit h a pipe flowing in and a pipe flowing out . You can change
t he valve cont r olling t he wat er t hat flows in, but t he out flow r at e depends on
t he diamet er of t he out flow pipe (which is const ant ) and t he pr essur e in t he
t ank (which var ies wit h t he wat er level). The syst em has some ver y nonlinear
char act er ist ics.
A cont r oller for t he wat er level in t he t ank needs t o know t he cur r ent wat er
level and it needs t o be able t o set t he valve. Our cont r oller ’s input will be t he
wat er level er r or (desir ed wat er level minus act ual wat er level) and it s out put
will be t he r at e at which t he valve is opening or closing. A fir st pass at wr it ing
a fuzzy cont r oller for t his syst em might be t he following.
1. If (level is okay) then (valve is no_change) (1)
2. If (level is low) then (valve is open_fast) (1)
3. If (level is high) then (valve is close_fast) (1)
One of t he gr eat advant ages of t he Fuzzy Logic Toolbox is t he abilit y t o t ake
fuzzy syst ems dir ect ly int o Simulink and t est t hem out in a simulat ion
envir onment . A Simulink block diagr am for t his syst em is shown below. It
Working with Simulink
279
cont ains a Simulink block called t he Fuzzy Logic Cont r oller block. The
Simulink block diagr am for t his syst em is sltank. Typing
sltank
at t he command line, causes t he syst em t o appear .
At t he same t ime, t he file tank.fis is loaded int o t he FIS st r uct ur e tank.
2 Tutorial
280
Some exper iment at ion shows t hat t hr ee r ules ar e not sufficient , since t he
wat er level t ends t o oscillat e ar ound t he desir ed level. This is seen fr om t he plot
below.
We need t o add anot her input , t he wat er level’s r at e of change, t o slow down
t he valve movement when we get close t o t he r ight level.
4. If (level is good) and (rate is negative) then (valve is close_slow) (1)
5. If (level is good) and (rate is positive) then (valve is open_slow) (1)
The demo, sltank is built wit h t hese five r ules. You can examine Wit h all five
r ules in oper at ions, t he st ep r esponse by simulat ing t his syst em. This is done
by clicking on Start fr om t he pulldown menu under Si mulate, and clicking on
t he Compari s on block. The r esult looks like t his
One int er est ing feat ur e of t he wat er t ank syst em is t hat t he t ank empt ies much
mor e slowly t han it fills up because of t he specific value of t he out flow diamet er
pipe. We can deal wit h t his by set t ing t he close_slow valve member ship
funct ion t o be slight ly differ ent fr om t he open_slow set t ing. A PID cont r oller
does not have t his capabilit y. The valve command ver sus t he wat er 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
281
change r at e (depict ed as water) and t he r elat ive wat er level change (depict ed
as level) sur face looks like t his. If you look closely, you can see a slight
asymmet r y t o t he plot .
Because t he MATLAB t echnical comput ing envir onment suppor t s so many
t ools (like t he Cont r ol Syst em Toolbox, t he Neur al Net wor k Toolbox, t he
Nonlinear Cont r ol Design Blockset , and so on), you can, for example, easily
make a compar ison of a fuzzy cont r oller ver sus a linear cont r oller or a neur al
net wor k cont r oller .
For a demonst r at ion of how t he Rule Viewer can be used t o int er act wit h a
Fuzzy Logic Cont r oller block in a Simulink model, t ype
sltankrule
This demo cont ains a block called t he Fuzzy Cont r oller Wit h Rule Viewer block.
In t his demo, t he Rule Viewer opens when you st ar t t he Simulink simulat ion.
This Rule Viewer pr ovides an animat ion of how t he r ules ar e fir ed dur ing t he
−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
282
wat er t ank simulat ion. The windows t hat open when you simulat e t he
sltankrule demo ar e depict ed as follows:
The Rule Viewer t hat opens dur ing t he simulat ion can be used t o access t he
Member ship Funct ion Edit or , t he Rule Edit or , or any of t he ot her GUIs, (see
“The Member ship Funct ion Edit or ” on page 252, or “The Rule Edit or ” on page
256, for mor e infor mat ion).
Working with Simulink
283
For example, you may want t o open t he Rule Edit or t o change one of your r ules.
To do so, select t he Edi t rules menu it em under t he Vi ew menu of t he open
Rule Viewer . Now you can view or edit t he r ules for t his Simulink model:
It ’s best if you st op t he simulat ion pr ior t o select ing any of t hese edit or s t o
change your FIS. Remember t o save any changes you make t o your FIS t o t he
wor kspace befor e you r est ar t t he simulat ion.
Building Your Own Fuzzy Simulink Models
To build your own Simulink syst ems t hat use fuzzy logic, simply copy t he Fuzzy
Logic Cont r oller block out of sltank (or any of t he ot her Simulink demo
syst ems available wit h t he t oolbox) and place it in your own block diagr am. You
can also open t he Simulink libr ar y called fuzblock, which cont ains t he Fuzzy
Logic Cont r oller block, t he Fuzzy Cont r oller Wit h Rule Viewer block, and
sever al demo blocks. To access t hese blocks, t ype
fuzblock
2 Tutorial
284
at t he MATLAB pr ompt . The following libr ar y appear s:
When you use t hese blocks, make sur e t hat t he fuzzy infer ence syst em (FIS)
st r uct ur e cor r esponding t o your fuzzy syst em is bot h in t he MATLAB
wor kspace, and r efer r ed t o by name in t he dialog box associat ed wit h t he Fuzzy
Logic Cont r oller block.
Doubleclick on t he Fuzzy Cont r oller Wit h Rule Viewer block, and t he following
appear s:
This block uses t he zer oor der hold met hod for sampling.
The Fuzzy Logic Cont r oller block is a masked Simulink block based on t he
Sfunct ion sffis.mex. This funct ion is it self based on t he same algor it hms as
t he funct ion evalfis, but it has been t ailor ed t o wor k opt imally wit hin t he
Working with Simulink
285
Simulink envir onment . For mor e descr ipt ions of t hese, see fuzblock on page
327, and sffis on page 365.
2 Tutorial
286
SugenoType Fuzzy Inference
The fuzzy infer ence pr ocess we’ve been r efer r ing t o so far is known as
Mamdani’s fuzzy infer ence met hod. It ’s t he most commonly seen fuzzy
met hodology. In t his sect ion we discuss t he socalled Sugeno, or
TakagiSugenoKang met hod of fuzzy infer ence fir st int r oduced in 1985
[Sug85]. It is similar t o t he Mamdani met hod in many r espect s. In fact t he fir st
t wo par t s of t he fuzzy infer ence pr ocess, fuzzifying t he input s and applying t he
fuzzy oper at or , ar e exact ly t he same. The main differ ence bet ween
Mamdanit ype of fuzzy infer ence and Sugenot ype is t hat t he out put
member ship funct ions ar e only linear or const ant for Sugenot ype fuzzy
infer ence.
A t ypical fuzzy r ule in a zeroorder S ugeno fuzzy model has t he for m
if x is A and y is B t hen z = k
wher e A and B ar e fuzzy set s in t he ant ecedent , while k is a cr isply defined
const ant in t he consequent . When t he out put of each r ule is a const ant like t his,
t he similar it y wit h Mamdani’s met hod is st r iking. The only dist inct ions ar e t he
fact t hat all out put member ship funct ions ar e singlet on spikes, and t he
implicat ion and aggr egat ion met hods ar e fixed and can not be edit ed. The
implicat ion met hod is simply mult iplicat ion, and t he aggr egat ion oper at or just
includes all of t he singlet ons.
SugenoType Fuzzy Inference
287
The figur e above shows t he fuzzy t ipping model developed in pr evious sect ions
of t his manual adapt ed for use as a zer oor der Sugeno syst em. For t unat ely it is
fr equent ly t he case t hat singlet on out put funct ions ar e complet ely sufficient for
a given pr oblem’s needs. As an example, t he syst em tippersg.fis is t he
Sugenot ype r epr esent at ion of t he nowfamiliar t ipping model. If you load t he
5. Defuzzi fy
(wei ghted
average)
4. Apply
aggregati on
method (max).
2. Apply
fuzzy
operati on
(O R = max)
1. Fuzzi fy i nputs
3. Apply
i mpli cati on
method (mi n).
delicious
average
good
excellent
rancid cheap poor
generous
food = 8
input 2 output
rule 2 ha s
no d ep end ency
on i np ut 2
tip = 16.3%
service = 3
input 1
If service i s poor food i s rancid tip = cheap then or
If service i s good then tip = average
If service i s excellent food i s delicious then or tip = generous
1.
2.
3.
2 Tutorial
288
syst em and plot it s out put sur face, you will see it is almost t he same as t he
Mamdani syst em we’ve been looking at .
a = readfis('tippersg');
gensurf(a)
The mor e gener al firstorder S ugeno fuzzy model has r ules of t he for m
if x is A and y is B t hen z = p*x + q*y + r
wher e A and B ar e fuzzy set s in t he ant ecedent , while p, q, and r ar e all
const ant s. The easiest way t o visualize t he fir st or der syst em is t o t hink of each
r ule as defining t he locat ion of a “moving singlet on.” That is, t he singlet on
out put spikes can move ar ound in a linear fashion in t he out put space,
depending on what t he input is. This also t ends t o make t he syst em not at ion
ver y compact and efficient . Higher or der Sugeno fuzzy models ar e possible, but
t hey int r oduce significant complexit y wit h lit t le obvious mer it . Sugeno fuzzy
models whose out put member ship funct ions ar e gr eat er t han fir st or der ar e not
suppor t ed by t he Fuzzy Logic Toolbox.
Because of t he linear dependence of each r ule on t he syst em’s input var iables,
t he Sugeno met hod is ideal for act ing as an int er polat ing super visor of mult iple
linear cont r oller s t hat ar e t o be applied, r espect ively, t o differ ent oper at ing
condit ions of a dynamic nonlinear syst em. For example, t he per for mance of an
air cr aft may change dr amat ically wit h alt it ude and Mach number . Linear
cont r oller s, t hough easy t o comput e and wellsuit ed t o any given flight
condit ion, must be updat ed r egular ly and smoot hly t o keep up wit h t he
changing st at e of t he flight vehicle. A Sugeno fuzzy infer ence syst em is
0
2
4
6
8
10
0
2
4
6
8
10
10
15
20
service
food
t
i
p
SugenoType Fuzzy Inference
289
ext r emely well suit ed t o t he t ask of smoot hly int er polat ing t he linear gains
t hat would be applied acr oss t he input space; it ’s a nat ur al and efficient gain
scheduler . Similar ly, a Sugeno syst em is suit ed for modeling nonlinear syst ems
by int er polat ing mult iple linear models.
An Example: Two Lines
To see a specific example of a syst em wit h linear out put member ship funct ions,
consider t he one input one out put syst em st or ed in sugeno1.fis.
fismat = readfis('sugeno1');
getfis(fismat,'output',1)
Name = output
NumMFs = 2
MFLabels =
line1
line2
Range = [0 1]
The out put var iable has t wo member ship funct ions:
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
Fur t her , t hese member ship funct ions ar e linear funct ions of t he input var iable.
The member ship funct ion line1 is defined by t he equat ion
output = (1)*input + (1)
and t he member ship funct ion line2 is defined by t he equat ion
output = (1)*input + (1)
2 Tutorial
290
The input member ship funct ions and r ules define which of t hese out put
funct ions will be expr essed 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)
The funct ion plotmf shows us t hat t he member ship funct ion low gener ally
r efer s t o input values less t han zer o, while high r efer s t o values gr eat er t han
zer o. The funct ion gensurf shows how t he over all fuzzy syst em out put swit ches
smoot hly fr om t he line called line1 t o t he line called line2.
subplot(2,1,1), plotmf(fismat,'input',1)
subplot(2,1,2), gensurf(fismat)
This is just one example of how a Sugenot ype syst em gives you t he fr eedom t o
incor por at e linear syst ems int o your fuzzy syst ems. By ext ension, you could
build a fuzzy syst em t hat swit ches bet ween sever al opt imal linear cont r oller s
as a highly nonlinear syst em moves ar ound in it s oper at ing space.
Conclusion
Because it is a mor e compact and comput at ionally efficient r epr esent at ion t han
a Mamdani syst em, t he Sugeno syst em lends it self t o t he use of adapt ive
t echniques for const r uct ing fuzzy models. These adapt ive t echniques can be
used t o cust omize t he member ship funct ions so t hat t he fuzzy syst em best
models t he dat a.
−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
SugenoType Fuzzy Inference
291
Note on FIS Conversion: The MATLAB command line funct ion mam2sug can
be used t o conver t a Mamdani syst em int o a Sugeno syst em (not necessar ily
wit h a single out put ) wit h const ant out put member ship funct ions. It uses t he
cent r oid associat ed wit h all of t he out put member ship funct ions of t he
Mamdani syst em. See Chapt er 3 for det ails.
Her e ar e some final consider at ions about t he t wo differ ent met hods:
Advantages of the Sugeno method
•It ’s comput at ionally efficient .
•It wor ks well wit h linear t echniques (e.g., PID cont r ol).
•It wor ks well wit h opt imizat ion and adapt ive t echniques.
•It has guar ant eed cont inuit y of t he out put sur face.
•It ’s wellsuit ed t o mat hemat ical analysis.
Advantages of the Mamdani method
•It ’s int uit ive.
•It has widespr ead accept ance.
•It ’s wellsuit ed t o human input .
2 Tutorial
292
anfis and the ANFIS Editor GUI
The basic st r uct ur e of t he t ype of fuzzy infer ence syst em t hat we’ve seen t hus
far is a model t hat maps input char act er ist ics t o input member ship funct ions,
input member ship funct ion t o r ules, r ules t o a set of out put char act er ist ics,
out put char act er ist ics t o out put member ship funct ions, and t he out put
member ship funct ion t o a singlevalued out put or a decision associat ed wit h
t he out put . We have only consider ed member ship funct ions t hat have been
fixed, and somewhat ar bit r ar ily chosen. Also, we’ve only applied fuzzy
infer ence t o modeling syst ems whose r ule st r uct ur e is essent ially
pr edet er mined by t he user ’s int er pr et at ion of t he char act er ist ics of t he
var iables in t he model.
In t his sect ion we discuss t he use of t he funct ion anfis and t he ANFIS Edit or
GUI in t he Fuzzy Logic Toolbox. These t ools apply fuzzy infer ence t echniques
t o dat a modeling. As you have seen fr om t he ot her fuzzy infer ence GUIs, t he
shape of t he member ship funct ions depends on par amet er s, and changing
t hese par amet er s will change t he shape of t he member ship funct ion. Inst ead of
just looking at t he dat a t o choose t he member ship funct ion par amet er s, we will
see how member ship funct ion par amet er s can be chosen aut omat ically using
t hese Fuzzy Logic Toolbox applicat ions.
A Modeling Scenario
Suppose you want t o apply fuzzy infer ence t o a syst em for which you alr eady
have a collect ion of input /out put dat a t hat you would like t o use for modeling,
modelfollowing, or some similar scenar io. You don’t necessar ily have a
pr edet er mined model st r uct ur e based on char act er ist ics of var iables in your
syst em.
Ther e will be some modeling sit uat ions in which you can’t just look at t he dat a
and discer n what t he member ship funct ions should look like. Rat her t han
choosing t he par amet er s associat ed wit h a given member ship funct ion
ar bit r ar ily, t hese par amet er s could be chosen so as t o t ailor t he member ship
funct ions t o t he input /out put dat a in or der t o account for t hese t ypes of
var iat ions in t he dat a values. This is wher e t he socalled neuroadaptive
lear ning t echniques incor por at ed int o anfis in t he Fuzzy Logic Toolbox can
help.
anfis and the ANFIS Editor GUI
293
Model Learning and Inference Through ANFIS
The basic idea behind t hese neur oadapt ive lear ning t echniques is ver y simple.
These t echniques pr ovide a met hod for t he fuzzy modeling pr ocedur e t o learn
infor mat ion about a dat a set , in or der t o comput e t he member ship funct ion
par amet er s t hat best allow t he associat ed fuzzy infer ence syst em t o t r ack t he
given input /out put dat a. This lear ning met hod wor ks similar ly t o t hat of
neur al net wor ks. The Fuzzy Logic Toolbox funct ion t hat accomplishes t his
member ship funct ion par amet er adjust ment is called anfis. anfis can be
accessed eit her fr om t he command line, or t hr ough t he ANFIS Edit or GUI.
Since t he funct ionalit y of t he command line funct ion anfis and t he ANFIS
Edit or GUI is similar , t hey ar e used somewhat int er changeably in t his
discussion, unt il we dist inguish t hem t hr ough t he descr ipt ion of t he GUI.
What Is ANFIS?
The acr onym ANFIS der ives it s name fr om adaptive neurofuzzy inference
system. Using a given input /out put dat a set , t he t oolbox funct ion anfis
const r uct s a fuzzy infer ence syst em (FIS) whose member ship funct ion
par amet er s ar e t uned (adjust ed) using eit her a backpr opagat ion algor it hm
alone, or in combinat ion wit h a least squar es t ype of met hod. This allows your
fuzzy syst ems t o lear n fr om t he dat a t hey ar e modeling.
FIS Structure and Parameter Adjustment
A net wor kt ype st r uct ur e similar t o t hat of a neur al net wor k, which maps
input s t hr ough input member ship funct ions and associat ed par amet er s, and
t hen t hr ough out put member ship funct ions and associat ed par amet er s t o
out put s, can be used t o int er pr et t he input /out put map.
The par amet er s associat ed wit h t he member ship funct ions will change
t hr ough t he lear ning pr ocess. The comput at ion of t hese par amet er s (or t heir
adjust ment ) is facilit at ed by a gr adient vect or , which pr ovides a measur e of
how well t he fuzzy infer ence syst em is modeling t he input /out put dat a for a
given set of par amet er s. Once t he gr adient vect or is obt ained, any of sever al
opt imizat ion r out ines could be applied in or der t o adjust t he par amet er s so as
t o r educe some er r or measur e (usually defined by t he sum of t he squar ed
differ ence bet ween act ual and desir ed out put s). anfis uses eit her back
pr opagat ion or a combinat ion of least squar es est imat ion and backpr opagat ion
for member ship funct ion par amet er est imat ion.
2 Tutorial
294
Familiarity Breeds Validation: Know Your Data
The modeling appr oach used by anfis is similar t o many syst em ident ificat ion
t echniques. Fir st , you hypot hesize a par amet er ized model st r uct ur e (r elat ing
input s t o member ship funct ions t o r ules t o out put s t o member ship funct ions,
and so on). Next , you collect input /out put dat a in a for m t hat will be usable by
anfis for t r aining. You can t hen use anfis t o train t he FIS model t o emulat e
t he t r aining dat a pr esent ed t o it by modifying t he member ship funct ion
par amet er s accor ding t o a chosen er r or cr it er ion.
In gener al, t his t ype of modeling wor ks well if t he t r aining dat a pr esent ed t o
anfis for t r aining (est imat ing) member ship funct ion par amet er s is fully
r epr esent at ive of t he feat ur es of t he dat a t hat t he t r ained FIS is int ended t o
model. This is not always t he case, however . In some cases, dat a is collect ed
using noisy measur ement s, and t he t r aining dat a cannot be r epr esent at ive of
all t he feat ur es of t he dat a t hat will be pr esent ed t o t he model. This is wher e
model validation comes int o play.
Model Validation Using Checking and Testing Data Sets
Model validat ion is t he pr ocess by which t he input vect or s fr om input /out put
dat a set s on which t he FIS was not t r ained, ar e pr esent ed t o t he t r ained FIS
model, t o see how well t he FIS model pr edict s t he cor r esponding dat a set
out put values. This is accomplished wit h t he ANFIS Edit or GUI using t he
socalled testing data set, and it s use is descr ibed in a subsect ion t hat follows.
You can also use anot her t ype of dat a set for model validat ion in anfis. This
ot her t ype of validat ion dat a set is r efer r ed t o as t he checking data set and t his
set is used t o cont r ol t he pot ent ial for t he model over fit t ing t he dat a. When
checking dat a is pr esent ed t o anfis as well as t r aining dat a, t he FIS model is
select ed t o have par amet er s associat ed wit h t he minimum checking dat a model
er r or .
One pr oblem wit h model validat ion for models const r uct ed using adapt ive
t echniques is select ing a dat a set t hat is bot h r epr esent at ive of t he dat a t he
t r ained model is int ended t o emulat e, yet sufficient ly dist inct fr om t he t r aining
dat a set so as not t o r ender t he validat ion pr ocess t r ivial. If you have collect ed
a lar ge amount of dat a, hopefully t his dat a cont ains all t he necessar y
r epr esent at ive feat ur es, so t he pr ocess of select ing a dat a set for checking or
t est ing pur poses is made easier . However , if you expect t o be pr esent ing noisy
measur ement s t o your model, it ’s possible t he t r aining dat a set does not
include all of t he r epr esent at ive feat ur es you want t o model.
anfis and the ANFIS Editor GUI
295
The basic idea behind using a checking dat a set for model validat ion is t hat
aft er a cer t ain point in t he t r aining, t he model begins over fit t ing t he t r aining
dat a set . In pr inciple, t he model er r or for t he checking dat a set t ends t o
decr ease as t he t r aining t akes place up t o t he point t hat over fit t ing begins, and
t hen t he model er r or for t he checking dat a suddenly incr eases. In t he fir st
example in t he following sect ion, t wo similar dat a set s ar e used for checking
and t r aining, but t he checking dat a set is cor r upt ed by a small amount of noise.
This example illust r at es of t he use of t he ANFIS Edit or GUI wit h checking
dat a t o r educe t he effect of model over fit t ing. In t he second example, a t r aining
dat a set t hat is pr esent ed t o anfis is sufficient ly differ ent t han t he applied
checking dat a set . By examining t he checking er r or sequence over t he t r aining
per iod, it is clear t hat t he checking dat a set is not good for model validat ion
pur poses. This example illust r at es t he use of t he ANFIS Edit or GUI t o compar e
dat a set s.
Some Constraints of anfis
anfis is much mor e complex t han t he fuzzy infer ence syst ems discussed so far ,
and is not available for all of t he fuzzy infer ence syst em opt ions. Specifically,
anfis only suppor t s Sugenot ype syst ems, and t hese must be:
•Fir st or zer ot h or der Sugenot ype syst ems
•Single out put , obt ained using weight ed aver age defuzzificat ion (linear or
const ant out put member ship funct ions)
•Of unit y weight for each r ule
An er r or occur s if your FIS st r uct ur e does not comply wit h t hese const r aint s.
Mor eover , anfis cannot accept all t he cust omizat ion opt ions t hat basic fuzzy
infer ence allows. That is, you cannot make your own member ship funct ions
and defuzzificat ion funct ions; you’ll have t o use t he ones pr ovided.
The ANFIS Editor GUI
To get st ar t ed wit h t he ANFIS Edit or GUI, t ype
anfisedit
The following GUI will appear on your scr een.
2 Tutorial
296
Fr om t his GUI you can
•Load dat a (t r aining, t est ing, and checking) by select ing appr opr iat e r adio
but t ons in t he Load data por t ion of t he GUI and t hen select ing Load Data...
The loaded dat a is plot t ed on t he plot r egion.
•Gener at e an init ial FIS model or load an init ial FIS model using t he opt ions
in t he Generate FIS por t ion of t he GUI
•View t he FIS model st r uct ur e once an init ial FIS has been gener at ed or
loaded by select ing t he Structure but t on
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.
Cl ear Dat a 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
297
•Choose t he FIS model par amet er opt imizat ion met hod: backpr opagat ion or a
mixt ur e of backpr opagat ion and least squar es (hybr id met hod)
•Choose t he number of t r aining epochs and t he t r aining er r or t oler ance
•Tr ain t he FIS model by select ing t he Trai n Now but t on
This t r aining adjust s t he member ship funct ion par amet er s and plot s t he
t r aining (and/or checking dat a) er r or plot (s) in t he plot r egion.
•View t he FIS model out put ver sus t he t r aining, checking, or t est ing dat a
out put by select ing t he Te st Now but t on
This funct ion plot s t he t est dat a against t he FIS out put in t he plot r egion.
You can also use t he ANFIS Edit or GUI menu bar t o load an FIS t r aining
init ializat ion, save your t r ained FIS, open a new Sugeno syst em, or open any
of t he ot her GUIs t o int er pr et t he t r ained FIS model.
Data Formalities and the ANFIS Editor GUI: Checking and Training
To st ar t t r aining an FIS using eit her anfis or t he ANFIS Edit or GUI, fir st you
need t o have a t r aining dat a set t hat cont ains desir ed input /out put dat a pair s
of t he t ar get syst em t o be modeled. Somet imes you also want t o have t he
opt ional t est ing dat a set t hat can check t he gener alizat ion capabilit y of t he
r esult ing fuzzy infer ence syst em, and/or a checking dat a set t hat helps wit h
model over fit t ing dur ing t he t r aining. The use of a t est ing dat a set and a
checking dat a set for model validat ion is discussed in “Model Validat ion Using
Checking and Test ing Dat a Set s” on page 294. As we ment ioned pr eviously,
over fit t ing is account ed for by t est ing t he FIS t r ained on t he t r aining dat a
against t he checking dat a, and choosing t he member ship funct ion par amet er s
t o be t hose associat ed wit h t he minimum checking er r or if t hese er r or s indicat e
model over fit t ing. You will have t o examine your t r aining er r or plot s fair ly
closely in or der t o det er mine t his. These issues ar e discussed lat er in an
example. Usually t hese t r aining and checking dat a set s ar e collect ed based on
obser vat ions of t he t ar get syst em and ar e t hen st or ed in separ at e files.
Note on Data Format: Any dat a set you load int o t he ANFIS Edit or GUI, (or
t hat is applied t o t he command line funct ion anfis) must be a mat r ix wit h t he
input dat a ar r anged as vect or s in all but t he last column. The out put dat a
must be in t he last column.
2 Tutorial
298
ANFIS Editor GUI Example 1: Checking Data Helps
Model Validation
In t his sect ion we look at an example t hat loads similar t r aining and checking
dat a set s, only t he checking dat a set is cor r upt ed by noise.
Loading Data
To wor k bot h of t he following examples, you load t he t r aining dat a set s
(fuzex1trnData and fuzex2trnData) and t he checking dat a set s
(fuzex1chkData and fuzex2chkData), int o t he ANFIS Edit or GUI fr om t he
wor kspace. You may also subst it ut e your own dat a set s.
To load t hese dat a set s fr om t he dir ect or y fuzzydemos int o t he MATLAB
wor kspace, t ype
load fuzex1trnData.dat
load fuzex2trnData.dat
load fuzex1chkData.dat
load fuzex2chkData.dat
fr om t he command line.
Note on loading data: You may also want t o load your dat a set fr om t he
fuzzydemos or any ot her dir ect or y on t he disk, using t he ANFIS Edit or GUI,
dir ect ly.
Open t he ANFIS Edit or GUI by t yping anfisedit. To load t he t r aining dat a
set , click on Trai ni ng, worksp. and t hen Load Data....
The small GUI window t hat pops up allows you t o t ype in a var iable name fr om
t he wor kspace. Type in fuzex1trnData, as shown below.
anfis and the ANFIS Editor GUI
299
The t r aining dat a appear s in t he plot in t he cent er of t he GUI as a set of circles.
Not ice t he hor izont al axis is mar ked data se t i nde x. This index indicat es t he
r ow fr om which t hat input dat a value was obt ained (whet her or not t he input
is a vect or or a scalar ). Next click on Checki ng in t he Type column of t he Load
2 Tutorial
2100
data por t ion of t he GUI t o load fuzex1chkData fr om t he wor kspace. This dat a
appear s in t he GUI plot as plusses super imposed on t he t r aining dat a.
This dat a set will be used t o t r ain a fuzzy syst em by adjust ing t he member ship
funct ion par amet er s t hat best model t his dat a. The next st ep is t o specify an
init ial fuzzy infer ence syst em for anfis t o t r ain.
Initializing and Generating Your FIS
You can eit her init ialize t he FIS par amet er s t o your own pr efer ence, or if you
do not have any pr efer ence for how you want t he init ial member ship funct ions
t o be par amet er ized, you can let anfis do t his for you.
Automatic FIS Structure Generation with ANFIS
To init ialize your FIS using anfis:
1 Choose Gri d parti ti on, t he default par t it ioning met hod. (The t wo par t it ion
met hods, gr id par t it ioning and subt r act ive clust er ing, ar e descr ibed lat er in
+++ Checking data
ooo Training data
anfis and the ANFIS Editor GUI
2101
“Fuzzy CMeans Clust er ing” on page 2120, and in “Subt r act ive Clust er ing”
on page 2123.
2 Click on t he Ge nerate FIS but t on. This br ings up a menu fr om which you
can choose t he number of member ship funct ions, MFs, and t he t ype of input
and out put member ship funct ions. Not ice t her e ar e only t wo choices for t he
out put member ship funct ion: cons tant and li ne ar. This limit at ion of out put
member ship funct ion choices is because anfis only oper at es on Sugenot ype
syst ems.
3 Fill in t he ent r ies as we’ve done below, and click on OK.
You can also implement t his FIS gener at ion fr om t he command line using t he
command genfis1 (for gr id par t it ioning) or genfis2 (for subt r act ive
clust er ing). A command line language example illust r at ing t he use of genfis1
and anfis is pr ovided lat er .
Specifying Your Own Membership Functions for ANFIS
Alt hough we don’t expect you t o do t his for t his example, you can choose your
own pr efer r ed member ship funct ions wit h specific par amet er s t o be used by
anfis as an init ial FIS for t r aining.
2 Tutorial
2102
To define your own FIS st r uct ur e and par amet er s:
1 Open t he Edi t me mbers hi p functi ons menu it em fr om t he Vi ew menu.
2 Add your desir ed member ship funct ions (t he cust om member ship opt ion will
be disabled for anfis). The out put member ship funct ions must eit her be all
const ant or all linear . For car r ying out t his and t he following st ep, see “The
FIS Edit or ” on page 249 and “The Member ship Funct ion Edit or ” on page
252.
3 Select t he Edi t rule s menu it em in t he Vi e w menu. Use t he Rule Edit or t o
gener at e t he r ules (see“The Rule Edit or ” on page 256).
4 Select t he Edi t FIS properti e s menu it em fr om t he Vi ew menu. Name your
FIS, and save it t o eit her t he wor kspace or t he disk.
5 Use t he Vi ew menu t o r et ur n t o t he ANFIS Edit or GUI t o t r ain t he FIS.
To load an exist ing FIS for ANFIS init ializat ion, in t he Generate FIS por t ion
of t he GUI, click on Load from works p. or Load from di s k. You will load your
FIS fr om t he disk if you have saved an FIS pr eviously t hat you would like t o
use. Ot her wise you will be loading your FIS fr om t he wor kspace. Eit her of
t hese r adio but t ons t oggle t he Gene rate FIS but t on t o Load.... Load your FIS
by clicking on t his but t on.
anfis and the ANFIS Editor GUI
2103
Viewing Your FIS Structure
Aft er you gener at e t he FIS, you can view t he model st r uct ur e by clicking on t he
Structure but t on in t he middle of t he r ight hand side of t he GUI. A new GUI
appear s, as follows:
The br anches in t his nodal gr aph ar e color coded t o indicat e whet her or not
and, not , or or, ar e used in t he r ules. Clicking on t he nodes indicat es
infor mat ion about t he st r uct ur e.
You can view t he member ship funct ions or t he r ules by opening eit her t he
Member ship Funct ion Edit or , or t he Rule Edit or fr om t he Vi e w menu.
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
2104
ANFIS Training
The t wo anfis par amet er opt imizat ion met hod opt ions available for FIS
t r aining ar e hybri d (t he default , mixed least squar es and backpr opagat ion)
and backpropa (backpr opagat ion). The Error Tole rance is used t o cr eat e a
t r aining st opping cr it er ion, which is r elat ed t o t he er r or size. The t r aining will
st op aft er t he t r aining dat a er r or r emains wit hin t his t oler ance. This is best left
set t o 0 if you don’t know how your t r aining er r or is going t o behave.
To st ar t t he t r aining:
•Leave t he opt imizat ion met hod at hybri d.
•Set t he number of t r aining epochs t o 40, under t he Epochs list ing on t he GUI
(t he default value is 3).
•Select Trai n Now.
The following should appear on your scr een:
Not ice how t he checking er r or decr eases up t o a cer t ain point in t he t r aining
and t hen it incr eases. This incr ease r epr esent s t he point of model over fit t ing.
anfis chooses t he model par amet er s associat ed wit h t he minimum checking
***
Training error
... Checking error
anfis and the ANFIS Editor GUI
2105
er r or (just pr ior t o t his jump point ). This is an example for which t he checking
dat a opt ion of anfis is useful.
Testing Your Data Against the Trained FIS
To t est your FIS against t he checking dat a, click on Checki ng data in t he Te st
FIS por t ion of t he GUI, and click on Tes t Now. Now when you t est t he checking
dat a against t he FIS it looks pr et t y good:
Note on loading more data with anfis: If you ar e ever loading dat a int o
anfis aft er clear ing pr eviously loaded dat a, you must make sur e t hat t he
newly loaded dat a set s have t he same number of input s as t he pr eviously
loaded ones did. Ot her wise you will have t o st ar t a new anfisedit session
fr om t he command line.
2 Tutorial
2106
Note on the Checking Data option and Clearing Data: If you don’t want t o
use t he checking dat a opt ion of anfis, don’t load any checking dat a befor e you
t r ain t he FIS. If you decide t o r et r ain your FIS wit h no checking dat a, you can
unload t he checking dat a in one of t wo ways. One met hod is t o click on t he
Che cki ng r adio but t on in t he Load data por t ion of t he GUI and t hen click on
Clear Data t o unload t he checking dat a. The ot her met hod you can use is t o
close t he GUI and go t o t he command line and r et ype anfisedit. In t his case
you will have t o r eload t he t r aining dat a. Aft er clear ing t he dat a, you will need
t o r egener at e your FIS. Once t he FIS is gener at ed you can use your fir st
t r aining exper ience t o decide on t he number of t r aining epochs you want for
t he second r ound of t r aining.
ANFIS Editor GUI Example 2: Checking Data Doesn’t
Validate Model
In t his example, we examine what happens when t he t r aining and checking
dat a set s ar e sufficient ly differ ent . We see how t he ANFIS Edit or GUI can be
used t o lear n somet hing about dat a set s and how t hey differ .
1 Clear bot h t he t r aining and checking dat a.
2 You can pr ess t he Cle ar Plot but t on on t he r ight , alt hough you don’t have t o.
3 Load fuzex2trnData and fuzex2chkData (r espect ively, t he t r aining dat a
and checking dat a) fr om t he MATLAB wor kspace just as you did in t he
pr evious example.
anfis and the ANFIS Editor GUI
2107
You should get somet hing t hat looks like t his:
+++ Checking data
ooo Training data
2 Tutorial
2108
Tr ain t he FIS for t his syst em exact ly as you did in t he pr evious example, except
now choose 60 Epochs befor e t r aining. You should get t he following:
Not ice t he checking er r or is quit e lar ge. It appear s t hat t he minimum checking
er r or occur s wit hin t he fir st epoch. Recall t hat using t he checking dat a opt ion
wit h anfis aut omat ically set s t he FIS par amet er s t o be t hose associat ed wit h
t he minimum checking er r or . Clear ly t his set of member ship funct ions would
not be t he best choice for modeling t he t r aining dat a.
What ’s wr ong her e? This example illust r at es t he pr oblem discussed ear lier
wher ein t he checking dat a set pr esent ed t o anfis for t r aining was sufficient ly
differ ent fr om t he t r aining dat a set . As a r esult , t he t r ained FIS did not capt ur e
t he feat ur es of t his dat a set ver y well. This illust r at es t he impor t ance of
knowing t he feat ur es of your dat a set well enough when you select your
t r aining and checking dat a. When t his is not t he case, you can analyze t he
checking er r or plot s t o see whet her or not t he checking dat a per for med
sufficient ly well wit h t he t r ained model. In t his example, t he checking er r or is
sufficient ly lar ge t o indicat e t hat eit her mor e dat a needs t o be select ed for
t r aining, or you may want t o modify your member ship funct ion choices (bot h
t he number of member ship funct ions and t he t ype). Ot her wise t he syst em can
***
Training error
... Checking error
anfis and the ANFIS Editor GUI
2109
be r et r ained wit hout t he checking dat a, if you t hink t he t r aining dat a capt ur es
sufficient ly t he feat ur es you ar e t r ying t o r epr esent .
To complet e t his example, let ’s t est t he t r ained FIS model against t he checking
dat a. To do so, click on Checki ng data in t he Te st FIS por t ion of t he GUI, and
click on Test Now. The following plot in t he GUI indicat es t hat t her e is quit e a
discr epancy bet ween t he checking dat a out put and t he FIS out put .
anfis from the Command Line
As you can see, gener at ing an FIS using t he ANFIS Edit or GUI is quit e simple.
However , as you saw in t he last example, you need t o be caut ious about
implement ing t he checking dat a validat ion feat ur e of anfis. You must check
t hat t he checking dat a er r or does what is supposed t o. Ot her wise you need t o
r et r ain t he FIS.
In t his sect ion we descr ibe how t o car r y out t he command line feat ur es of anfis
on a chaot ic t imesser ies pr edict ion example.
2 Tutorial
2110
Using anfis for Chaotic Time Series Prediction
The demo mgtsdemo uses anfis t o pr edict a t ime ser ies t hat is gener at ed by t he
following MackeyGlass (MG) t imedelay differ ent ial equat ion:
This t ime ser ies is chaot ic, and so t her e is no clear ly defined per iod. The ser ies
will not conver ge or diver ge, and t he t r aject or y is highly sensit ive t o init ial
condit ions. This is a benchmar k pr oblem in t he neur al net wor k and fuzzy
modeling r esear ch communit ies.
To obt ain t he t ime ser ies value at int eger point s, we applied t he four t hor der
RungeKut t a met hod t o find t he numer ical solut ion t o t he above MG equat ion;
t he r esult was saved in t he file mgdata.dat. Her e we assume x(0) = 1.2, τ = 17,
and x(t) = 0 for t < 0. To plot t he MG t ime ser ies, t ype
load mgdata.dat
t = mgdata(:, 1); x = mgdata(:, 2); plot(t, x);
In t imeser ies pr edict ion we want t o use known values of t he t ime ser ies up t o
t he point in t ime, say, t, t o pr edict t he value at some point in t he fut ur e, say,
t+P. The st andar d met hod for t his t ype of pr edict ion is t o cr eat e a mapping
x
·
t ( )
0.2x t τ – ( )
1 x
10
t τ – ( ) +
 0.1x t ( ) – =
anfis and the ANFIS Editor GUI
2111
fr om D sample dat a point s, sampled ever y ∆ unit s in t ime, (x(t(D1)∆),..., x(t ∆),
x(t )), t o a pr edict ed fut ur e value x(t +P). Following t he convent ional set t ings for
pr edict ing t he MG t ime ser ies, we set D = 4 and ∆ = P = 6. For each t, t he input
t r aining dat a for anfis is a four dimensional vect or of t he following for m:
w(t) = [x(t–18) x(t–12) x(t–6) x(t)]
The out put t r aining dat a cor r esponds t o t he t r aject or y pr edict ion:
s(t) = x(t+6)
For each t, r anging in values fr om 118 t o 1117, t he t r aining input /out put dat a
will be a st r uct ur e whose fir st component is t he four dimensional input w, and
whose second component is t he out put s. Ther e will be 1000 input /out put dat a
values. We use t he fir st 500 dat a values for t he anfis t r aining (t hese become
t he t r aining dat a set ), while t he ot her s ar e used as checking dat a for validat ing
t he ident ified fuzzy model. This r esult s in t wo 500point dat a st r uct ur es:
trnData and chkData.
Her e is t he code t hat gener at es t his dat a:
for t=118:1117,
Data(t117,:)=[x(t18) x(t12) x(t6) x(t) x(t+6)];
end
trnData=Data(1:500, :);
chkData=Data(501:end, :);
To st ar t t he t r aining, we need an FIS st r uct ur e t hat specifies t he st r uct ur e and
init ial par amet er s of t he FIS for lear ning. This is t he t ask of genfis1:
fismat = genfis1(trnData);
Since we did not specify number s and t ypes of member ship funct ions used in
t he FIS, default values ar e assumed. These default s pr ovide t wo gener alized
bell member ship funct ions on each of t he four input s, eight alt oget her . The
gener at ed FIS st r uct ur e cont ains 16 fuzzy r ules wit h 104 par amet er s. In or der
t o achieve good gener alizat ion capabilit y, it is impor t ant t o have t he number of
t r aining dat a point s be sever al t imes lar ger t han t he number par amet er s being
est imat ed. In t his case, t he r at io bet ween dat a and par amet er s is about five
(500/104).
2 Tutorial
2112
The funct ion genfis1 gener at es init ial member ship funct ions t hat ar e equally
spaced and cover t he whole input space. You can plot t he input member ship
funct ions using t he following commands.
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)
These init ial member ship funct ions ar e shown below.
To st ar t t he t r aining, t ype
[fismat1,error1,ss,fismat2,error2] = ...
anfis(trnData,fismat,[],[],chkData);
This t akes about four minut es on a Sun SPARCst at ion 2 for 10 epochs of
t r aining. Because t he checking dat a opt ion of anfis was invoked, t he final FIS
you choose would or dinar ily be t he one associat ed wit h t he minimum checking
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
2113
er r or . This is st or ed in fismat2. The following code will plot t hese new
member ship funct ions:
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)
Her e is t he r esult :.
To plot t he er r or signals t ype
plot([error1; error2]);
Her e error1 and error2 ar e t he r oot mean squar ed er r or for t he t r aining and
checking dat a, r espect ively.
In addit ion t o t hese er r or plot s, you may want t o plot t he FIS out put ver sus t he
t r aining or checking dat a. To compar e t he or iginal MG t ime ser ies and t he
fuzzy pr edict ion side by side, t r y
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
2114
subplot(211), plot(t(index), [x(index) anfis_output]);
subplot(212), plot(t(index), x(index) – anfis_output);
Not e t hat t he differ ence bet ween t he or iginal MG t ime ser ies and t he anfis
est imat ed values is ver y small. This is why you can only see one cur ve in t he
fir st plot . The pr edict ion er r or is shown in t he second plot wit h a much finer
scale. Not e t hat we have only t r ained for 10 epochs. Bet t er per for mance is
expect ed if we apply mor e ext ensive t r aining.
More on anfis and the ANFIS Editor GUI
The command anfis t akes at least t wo and at most six input ar gument s. The
gener al for mat is
[fismat1,trnError,ss,fismat2,chkError] = ...
anfis(trnData,fismat,trnOpt,dispOpt,chkData,method);
wher e trnOpt (t r aining opt ions), dispOpt (display opt ions), chkData (checking
dat a), and method (t r aining met hod), ar e opt ional. All of t he out put ar gument s
ar e also opt ional. In t his sect ion we discuss t he ar gument s and r ange
component s of t he command line funct ion anfis, as well as t he analogous
funct ionalit y of t he ANFIS Edit or GUI.
When t he ANFIS Edit or GUI is invoked using anfisedit, only t he t r aining
dat a set must exist pr ior t o implement ing anfis.In addit ion, t he st epsize will
be fixed when t he adapt ive neur ofuzzy syst em is t r ained using t his GUI t ool.
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
2115
Training Data
The t r aining dat a, trnData, is a r equir ed ar gument t o anfis, as well as t o t he
ANFIS Edit or GUI. Each r ow of trnData is a desir ed input /out put pair of t he
t ar get syst em t o be modeled. Each r ow st ar t s wit h an input vect or and is
followed by an out put value. Ther efor e, t he number of r ows of trnData is equal
t o t he number of t r aining dat a pair s, and, since t her e is only one out put , t he
number of columns of trnData is equal t o t he number of input s plus one.
Input FIS Structure
The input FIS st r uct ur e, fismat, can be obt ained eit her fr om any of t he fuzzy
edit or s: t he FIS Edit or , t he Member ship Funct ion Edit or , and t he Rule Edit or
fr om t he ANFIS Edit or GUI, (which allows an FIS st r uct ur e t o be loaded fr om
t he disk or t he wor kspace), or fr om t he command line funct ion, genfis1 (for
which you only need t o give number s and t ypes of member ship funct ions). The
FIS st r uct ur e cont ains bot h t he model st r uct ur e, (which specifies such it ems as
t he number of r ules in t he FIS, t he number of member ship funct ions for each
input , et c.), and t he par amet er s, (which specify t he shapes of member ship
funct ions). Ther e ar e t wo methods t hat anfis lear ning employs for updat ing
member ship funct ion par amet er s: backpr opagat ion for all par amet er s (a
st eepest descent met hod), and a hybr id met hod consist ing of backpr opagat ion
for t he par amet er s associat ed wit h t he input member ship funct ions, and least
squar es est imat ion for t he par amet er s associat ed wit h t he out put member ship
funct ions. As a r esult , t he t r aining er r or decr eases, at least locally, t hr oughout
t he lear ning pr ocess. Ther efor e, t he mor e t he init ial member ship funct ions
r esemble t he opt imal ones, t he easier it will be for t he model par amet er
t r aining t o conver ge. Human exper t ise about t he t ar get syst em t o be modeled
may aid in set t ing up t hese init ial member ship funct ion par amet er s in t he FIS
st r uct ur e.
Not e t hat genfis1 pr oduces an FIS st r uct ur e based on a fixed number of
member ship funct ions. This invokes t he socalled curse of dimensionality, and
causes an explosion of t he number of r ules when t he number of input s is
moder at ely lar ge, t hat is, mor e t han four or five. The Fuzzy Logic Toolbox offer s
a met hod t hat will pr ovide for some dimension r educt ion in t he fuzzy infer ence
syst em: you can gener at e an FIS st r uct ur e using t he clust er ing algor it hm
discussed in “Subt r act ive Clust er ing” on page 2123. Fr om t he ANFIS Edit or
GUI, t his algor it hm is select ed wit h a r adio but t on befor e t he FIS is gener at ed.
This subt r act ive clust er ing met hod par t it ions t he dat a int o gr oups called
clust er s, and gener at es an FIS wit h t he minimum number r ules r equir ed t o
dist inguish t he fuzzy qualit ies associat ed wit h each of t he clust er s.
2 Tutorial
2116
Training Options
The ANFIS Edit or GUI t ool allows you t o choose your desir ed er r or t oler ance
and number of t r aining epochs.
Tr aining opt ion trnOpt for t he command line anfis is a vect or t hat specifies
t he st opping cr it er ia and t he st epsize adapt at ion st r at egy:
•trnOpt(1): number of t r aining epochs, default = 10.
•trnOpt(2): er r or t oler ance, default = 0.
•trnOpt(3): init ial st epsize, default = 0.01.
•trnOpt(4): st epsize decr ease r at e, default = 0.9.
•trnOpt(5): st epsize incr ease r at e, default = 1.1.
If any element of trnOpt is an NaN or missing, t hen t he default value is t aken.
The t r aining pr ocess st ops if t he designat ed epoch number is r eached or t he
er r or goal is achieved, whichever comes fir st .
Usually we want t he st epsize pr ofile t o be a cur ve t hat incr eases init ially,
r eaches some maximum, and t hen decr eases for t he r emainder of t he t r aining.
This ideal st epsize pr ofile is achieved by adjust ing t he init ial st epsize and t he
incr ease and decr ease r at es (trnOpt(3)  trnOpt(5)). The default values ar e
set up t o cover a wide r ange of lear ning t asks. For any specific applicat ion, you
may want t o modify t hese st epsize opt ions in or der t o opt imize t he t r aining.
However , as we ment ioned pr eviously, t her e ar e no user specified st epsize
opt ions for t r aining t he adapt ive neur o fuzzy infer ence syst em gener at ed using
t he ANFIS Edit or GUI.
Display Options
Display opt ions only apply t o t he command line funct ion, anfis.
For t he command line anfis, t he display opt ions argument, dispOpt, is a vect or
of eit her ones or zer os t hat specifies what infor mat ion t o display, (pr int in t he
MATLAB command line window), befor e, dur ing, and aft er t he t r aining
pr ocess. One is used t o denot e print this option, wher eas zer o denot es don’t
print this option.
•dispOpt(1): display ANFIS infor mat ion, default = 1.
•dispOpt(2): display er r or (each epoch), default = 1.
•dispOpt(3): display st epsize (each epoch), default = 1.
•dispOpt(4): display final r esult s, default = 1.
anfis and the ANFIS Editor GUI
2117
The default mode is displays all available infor mat ion. If any element of
dispOpt is NaN or missing, t he default value will be t aken.
Method
Bot h t he ANFIS Edit or GUI and t he command line anfis apply eit her a
backpr opagat ion for m of t he st eepest descent met hod for member ship funct ion
par amet er est imat ion, or a combinat ion of backpr opagat ion and t he
least squar es met hod t o est imat e member ship funct ion par amet er s. The
choices for t his ar gument ar e hybrid or backpropagation. These met hod
choices ar e designat ed in t he command line funct ion, anfis, by 1 and 0,
r espect ively.
Output FIS Structure for Training Data
fismat1 is t he out put FIS st r uct ur e cor r esponding t o a minimal t r aining er r or .
This is t he FIS st r uct ur e t hat you will use t o r epr esent t he fuzzy syst em when
t her e is no checking dat a used for model cr ossvalidat ion. This dat a also
r epr esent s t he FIS st r uct ur e t hat is saved by t he ANFIS Edit or GUI when t he
checking dat a opt ion is not used.
When t he checking dat a opt ion is used, t he out put saved is t hat associat ed wit h
t he minimum checking er r or .
Training Error
The t r aining er r or is t he differ ence bet ween t he t r aining dat a out put value,
and t he out put of t he fuzzy infer ence syst em cor r esponding t o t he same
t r aining dat a input value, (t he one associat ed wit h t hat t r aining dat a out put
value). The t r aining er r or trnError r ecor ds t he r oot mean squar ed er r or
(RMSE) of t he t r aining dat a set at each epoch. fismat1 is t he snapshot of t he
FIS st r uct ur e when t he t r aining er r or measur e is at it s minimum. The ANFIS
Edit or GUI will plot t he t r aining er r or vs. epochs cur ve as t he syst em is
t r ained.
Stepsize
You cannot cont r ol t he st epsize opt ions wit h t he ANFIS Edit or GUI. Using t he
command line anfis, t he st epsize ar r ay ss r ecor ds t he st epsize dur ing t he
t r aining. Plot t ing ss gives t he st epsize pr ofile, which ser ves as a r efer ence for
adjust ing t he init ial st epsize and t he cor r esponding decr ease and incr ease
2 Tutorial
2118
r at es. The st epsize (ss) for t he command line funct ion anfis is updat ed
accor ding t o t he following guidelines:
•If t he er r or under goes four consecut ive r educt ions, incr ease t he st epsize by
mult iplying it by a const ant (ssinc) gr eat er t han one.
•If t he er r or under goes t wo consecut ive combinat ions of one incr ease and one
r educt ion, decr ease t he st epsize by mult iplying it by a const ant (ssdec) less
t han one.
The default value for t he init ial st epsize is 0.01; t he default values for ssinc
and ssdec ar e 1.1 and 0.9, r espect ively. All t he default values can be changed
via t he t r aining opt ion for t he command line anfis.
Checking Data
The checking dat a, chkData, is used for t est ing t he gener alizat ion capabilit y of
t he fuzzy infer ence syst em at each epoch. The checking dat a has t he same
for mat as t hat of t he t r aining dat a, and it s element s ar e gener ally dist inct fr om
t hose of t he t r aining dat a.
The checking dat a is impor t ant for lear ning t asks for which t he input number
is lar ge, and/or t he dat a it self is noisy. In gener al we want a fuzzy infer ence
syst em t o t r ack a given input /out put dat a set well. Since t he model st r uct ur e
used for anfis is fixed, t her e is a t endency for t he model t o over fit t he dat a on
which is it t r ained, especially for a lar ge number of t r aining epochs. If
over fit t ing does occur , we cannot expect t he fuzzy infer ence syst em t o r espond
well t o ot her independent dat a set s, especially if t hey ar e cor r upt ed by noise. A
validat ion or checking dat a set can be useful for t hese sit uat ions. This dat a set
is used t o cr ossvalidat e t he fuzzy infer ence model. This cr ossvalidat ion is
accomplished by applying t he checking dat a t o t he model, and seeing how well
t he model r esponds t o t his dat a.
When t he checking dat a opt ion is used wit h anfis, eit her via t he command
line, or using t he ANFIS Edit or GUI, t he checking dat a is applied t o t he model
at each t r aining epoch. When t he command line anfis is invoked, t he model
par amet er s t hat cor r espond t o t he minimum checking er r or ar e r et ur ned via
t he out put ar gument fismat2. The FIS member ship funct ion par amet er s
comput ed using t he ANFIS Edit or GUI when bot h t r aining and checking dat a
ar e loaded ar e associat ed wit h t he t r aining epoch t hat has a minimum checking
er r or .
anfis and the ANFIS Editor GUI
2119
The use of t he minimum checking dat a er r or epoch t o set t he member ship
funct ion par amet er s assumes
•The checking dat a is similar enough t o t he t r aining dat a t hat t he checking
dat a er r or will decr ease as t he t r aining begins
•The checking dat a incr eases at some point in t he t r aining, aft er which dat a
over fit t ing has occur r ed.
As discussed in “ANFIS Edit or GUI Example 2: Checking Dat a Doesn’t
Validat e Model” on page 2106, depending on t he behavior of t he checking dat a
er r or , t he r esult ing FIS may or may not be t he one you should be using.
Output FIS Structure for Checking Data
The out put of t he command line anfis, fismat2, is t he out put FIS st r uct ur e
wit h t he minimum checking er r or . This is t he FIS st r uct ur e t hat should be
used for fur t her calculat ion if checking dat a is used for cr oss validat ion.
Checking Error
The checking er r or is t he differ ence bet ween t he checking dat a out put value,
and t he out put of t he fuzzy infer ence syst em cor r esponding t o t he same
checking dat a input value, (t he one associat ed wit h t hat checking dat a out put
value). The checking er r or chkError r ecor ds t he RMSE for t he checking dat a
at each epoch. fismat2 is t he snapshot of t he FIS st r uct ur e when t he checking
er r or is at it s minimum. The ANFIS Edit or GUI will plot t he checking er r or vs.
epochs cur ve as t he syst em is t r ained.
2 Tutorial
2120
Fuzzy Clustering
Clust er ing of numer ical dat a for ms t he basis of many classificat ion and syst em
modeling algor it hms. The pur pose of clust er ing is t o ident ify nat ur al gr oupings
of dat a fr om a lar ge dat a set t o pr oduce a concise r epr esent at ion of a syst em’s
behavior . The Fuzzy Logic Toolbox is equipped wit h some t ools t hat allow you
t o find clust er s in input out put t r aining dat a. You can use t he clust er
infor mat ion t o gener at e a Sugenot ype fuzzy infer ence syst em t hat best models
t he dat a behavior using a minimum number of r ules. The r ules par t it ion
t hemselves accor ding t o t he fuzzy qualit ies associat ed wit h each of t he dat a
clust er s. This t ype of FIS gener at ion can be accomplished aut omat ically using
t he command line funct ion, genfis2.
Fuzzy CMeans Clustering
Fuzzy cmeans (FCM) is a dat a clust er ing t echnique wher ein each dat a point
belongs t o a clust er t o some degr ee t hat is specified by a member ship gr ade.
This t echnique was or iginally int r oduced by J im Bezdek in 1981 [Bez81] as an
impr ovement on ear lier clust er ing met hods. It pr ovides a met hod of how t o
gr oup dat a point s t hat populat e some mult idimensional space int o a specific
number of differ ent clust er s?
The Fuzzy Logic Toolbox command line funct ion fcm st ar t s wit h an init ial
guess for t he clust er cent er s, which ar e int ended t o mar k t he mean locat ion of
each clust er . The init ial guess for t hese clust er cent er s is most likely incor r ect .
Addit ionally, fcm assigns ever y dat a point a member ship gr ade for each
clust er . By it er at ively updat ing t he clust er cent er s and t he member ship gr ades
for each dat a point , fcm it er at ively moves t he clust er cent er s t o t he “r ight ”
locat ion wit hin a dat a set . This it er at ion is based on minimizing an object ive
funct ion t hat r epr esent s t he dist ance fr om any given dat a point t o a clust er
cent er weight ed by t hat dat a point ’s member ship gr ade.
fcm is a command line funct ion whose out put is a list of clust er cent er s and
sever al member ship gr ades for each dat a point . You can use t he infor mat ion
r et ur ned by fcm t o help you build a fuzzy infer ence syst em by cr eat ing
member ship funct ions t o r epr esent t he fuzzy qualit ies of each clust er .
Fuzzy Clustering
2121
An Example: 2D Clusters
Let ’s use some quasir andom t wodimensional dat a t o illust r at e how FCM
clust er ing wor ks. Load a dat a set and t ake a look at it .
load fcmdata.dat
plot(fcmdata(:,1),fcmdata(:,2),'o')
Now we invoke t he command line funct ion, fcm, and ask it t o find t wo clust er s
in t his dat a set
[center,U,objFcn] = fcm(fcmdata,2);
Iteration count = 1, obj. fcn = 8.941176
Iteration count = 2, obj. fcn = 7.277177
and so on unt il t he object ive funct ion is no longer decr easing much at all.
The var iable center cont ains t he coor dinat es of t he t wo clust er cent er s, U
cont ains t he member ship gr ades for each of t he dat a point s, and objFcn
cont ains a hist or y of t he object ive funct ion acr oss t he it er at ions.
The fcm funct ion is an it er at ion loop built on t op of sever al ot her r out ines,
namely initfcm, which init ializes t he pr oblem, distfcm, which is used for
dist ance calculat ions, and stepfcm, which st eps t hr ough one it er at ion.
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
2122
Plot t ing t he object ive funct ion shows t he pr ogr ess of t he clust er ing.
plot(objFcn)
Finally her e is a plot displaying t he t wo separ at e clust er s as classified by t he
fcm r out ine. The following figur e is gener at ed 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
2123
Clust er cent er s ar e indicat ed in t he figur e below by t he lar ge char act er s.
Subtractive Clustering
Suppose we don’t have a clear idea how many clust er s t her e should be for a
given set of dat a. S ubtractive clustering, [Chi94], is a fast , onepass algor it hm
for est imat ing t he number of clust er s and t he clust er cent er s in a set of dat a.
The clust er est imat es obt ained fr om t he subclust funct ion can be used t o
init ialize it er at ive opt imizat ionbased clust er ing met hods (fcm) and model
ident ificat ion met hods (like anfis). The subclust funct ion finds t he clust er s by
using t he subt r act ive clust er ing met hod.
The genfis2 funct ion builds upon t he subclust funct ion t o pr ovide a fast ,
onepass met hod t o t ake input out put t r aining dat a and gener at e a
Sugenot ype fuzzy infer ence syst em t hat models t he dat a behavior .
An Example: Suburban Commuting
In t his example we apply t he genfis2 funct ion t o model t he r elat ionship
bet ween t he number of aut omobile t r ips gener at ed fr om an ar ea and t he ar ea’s
demogr aphics. Demogr aphic and t r ip dat a ar e fr om 100 t r affic analysis zones
in New Cast le Count y, Delawar e. Five demogr aphic fact or s ar e consider ed:
populat ion, number of dwelling unit s, vehicle owner ship, median household
income, and t ot al employment . Hence t he model has five input var iables and
one out put var iable.
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
2124
Load t he dat a by t yping
tripdata
subplot(2,1,1), plot(datin)
subplot(2,1,2), plot(datout)
tripdata cr eat es sever al var iables in t he wor kspace. Of t he or iginal 100 dat a
point s, we will use 75 dat a point s as t r aining dat a (datin and datout) and 25
dat a point s as checking dat a, (as well as for t est dat a t o validat e t he model).
The checking dat a input /out put pair s ar e denot ed by chkdatin and chkdatout.
The genfis2 funct ion gener at es a model fr om dat a using clust er ing, and
r equir es you t o specify a clust er r adius. The clust er r adius indicat es t he r ange
of influence of a clust er when you consider t he dat a space as a unit hyper cube.
Specifying a small clust er r adius will usually yield many small clust er s in t he
dat a, (r esult ing in many r ules). Specifying a lar ge clust er r adius will usually
yield a few lar ge clust er s in t he dat a, (r esult ing in fewer r ules). The clust er
r adius is specified as t he t hir d ar gument of genfis2. Her e we call t he genfis2
funct ion using a clust er r adius of 0.5.
fismat=genfis2(datin,datout,0.5);
genfis2 is a fast , onepass met hod t hat does not per for m any it er at ive
opt imizat ion. An FIS st r uct ur e is r et ur ned; t he model t ype for t he FIS
st r uct ur e is a fir st or der Sugeno model wit h t hr ee r ules. We can use evalfis t o
ver ify t he model.
fuzout=evalfis(datin,fismat);
trnRMSE=norm(fuzout–datout)/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
2125
trnRMSE =
0.5276
The var iable trnRMSE is t he r oot mean squar e er r or of t he syst em gener at ed by
t he t r aining dat a. To validat e t he gener alizabilit y of t he model, we apply t est
dat a t o t he FIS. For t his example, we use t he checking dat a for bot h checking
and t est ing t he FIS par amet er s.
chkfuzout=evalfis(chkdatin,fismat);
chkRMSE=norm(chkfuzout–chkdatout)/sqrt(length(chkfuzout))
chkRMSE =
0.6170
Not sur pr isingly, t he model doesn’t do quit e as good a job on t he t est ing dat a.
A plot of t he t est ing dat a r eveals t he differ ence.
plot(chkdatout)
hold on
plot(chkfuzout,'o')
hold off
At t his point , we can use t he opt imizat ion capabilit y of anfis t o impr ove t he
model. Fir st , we will t r y using a r elat ively shor t anfis t r aining (50 epochs)
wit hout implement ing t he checking dat a opt ion, but t est t he r esult ing FIS
model against t he t est dat a. The command line ver sion of t his is as follows:
fismat2=anfis([datin datout],fismat,[50 0 0.1]);
Aft er t he t r aining is done, we t ype:
0 5 10 15 20 25
0
1
2
3
4
5
6
7
8
9
2 Tutorial
2126
fuzout2=evalfis(datin,fismat2);
trnRMSE2=norm(fuzout2–datout)/sqrt(length(fuzout2))
trnRMSE2 =
0.3407
chkfuzout2=evalfis(chkdatin,fismat2);
chkRMSE2=norm(chkfuzout2–chkdatout)/sqrt(length(chkfuzout2))
chkRMSE2 =
0.5827
The model has impr oved a lot wit h r espect t o t he t r aining dat a, but only a lit t le
wit h r espect t o t he checking dat a. Her e is a plot of t he impr oved t est ing dat a.
plot(chkdatout)
hold on
plot(chkfuzout2,'o')
hold off
Her e we see t hat genfis2 can be used as a st andalone, fast met hod for
gener at ing a fuzzy model fr om dat a, or as a pr epr ocessor t o anfis for
det er mining t he init ial r ules. An impor t ant advant age of using a clust er ing
met hod t o find r ules is t hat t he r esult ant r ules ar e mor e t ailor ed t o t he input
dat a t han t hey ar e in an FIS gener at ed wit hout clust er ing. This r educes t he
pr oblem of combinat or ial explosion of r ules when t he input dat a has a high
dimension (t he dr eaded cur se of dimensionalit y).
Overfitting
Now let ’s consider what happens if we car r y out a longer (200 epoch) t r aining
of t his syst em using anfis, including it s checking dat a opt ion.
0 5 10 15 20 25
0
1
2
3
4
5
6
7
8
9
Fuzzy Clustering
2127
[fismat3,trnErr,stepSize,fismat4,chkErr]= ...
anfis([datin datout],fismat2,[200 0
0.1],[], ...
[chkdatin chkdatout]);
The long list of out put ar gument s r et ur ns a hist or y of t he st epsizes, t he RMSE
ver sus t he t r aining dat a, and t he RMSE ver sus t he checking dat a associat ed
wit h each t r aining epoch.
ANFIS training completed at epoch 200.
Minimal training RMSE = 0.326566
Minimal checking RMSE = 0.582545
This looks good. The er r or wit h t he t r aining dat a is t he lowest we’ve seen, and
t he er r or wit h t he checking dat a is also lower t han befor e, t hough not by much.
This suggest s t hat maybe we had got t en about as close as possible wit h t his
syst em alr eady. Maybe we have even gone so far as t o over fit t he syst em t o t he
t r aining dat a. Over fit t ing occur s when we fit t he fuzzy syst em t o t he t r aining
dat a so well t hat it no longer does a ver y good job of fit t ing t he checking dat a.
The r esult is a loss of gener alit y. A look at t he er r or hist or y against bot h t he
t r aining dat a and t he checking dat a r eveals much.
Her e we can see t hat t he t r aining er r or set t les at about t he 50
t h
epoch point . In
fact , t he smallest value of t he checking dat a er r or occur s at epoch 52, aft er
which it incr eases slight ly, even as anfis cont inues t o minimize t he er r or
against t he t r aining dat a all t he way t o epoch 200. Depending on t he specified
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
2128
er r or t oler ance, t his plot also indicat es t he model’s abilit y t o gener alize t he t est
dat a.
A Clustering GUI Tool
Ther e is also t he Clust er ing GUI, which implement s fcm and subclust, along
wit h all of t heir opt ions. It s use is fair ly selfevident .
The clust er ing GUI looks like t his, and is invoked using t he command line
funct ion, findcluster.
You can invoke findcluster wit h a dat a set dir ect ly, in or der t o open t he GUI
wit h a dat a set . The dat a set must have t he ext ension .dat. For example, t o
load t he dat a set , clusterdemo.dat, t ype findcluster('clusterdemo.dat').
You use t he pulldown t ab under Method t o change bet ween fcm (fuzzy
cmeans) and subtracti v (subt r act ive clust er ing). Mor e infor mat ion on t he
opt ions can be found in t he ent r ies for fcm on page 322, and subclust on page
372, r espect ively.
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 pulldown tabs.
or subtractive
Save the value of
the cluster center.
Fuzzy Clustering
2129
The Clust er ing GUI wor ks on mult idimensional dat a set s, but only displays
t wo of t hose dimensions. Use t he pulldown t abs under Xaxi s and Yaxi s t o
select which dat a dimension you want t o view.
2 Tutorial
2130
StandAlone CCode Fuzzy Inference Engine
In t he fuzzy/fuzzy dir ect or y of t he t oolbox, you can find t wo C files, fismain.c
and fis.c, which ar e pr ovided as t he sour ce codes for a st andalone fuzzy
infer ence engine. The st andalone Ccode fuzzy infer ence engine can r ead an
FIS file and an input dat a file t o per for m fuzzy infer ence dir ect ly, or it can be
embedded in ot her ext er nal applicat ions.
To compile t he st andalone fuzzy infer ence engine on a UNIX syst em, t ype
% cc –O –o fismain fismain.c –lm
(Not e t hat % is only symbolic of a UNIX pr ompt , and t hat you do not have t o
t ype fis.c explicit ly, since it is included in fismain.c.) Upon successful
compilat ion, t ype t he execut able command t o see how it wor ks:
% fismain
This pr ompt s t he following message:
% Usage: fismain data_file fis_file
This means t hat fismain needs t wo files t o do it s wor k: a dat a file cont aining
r ows of input vect or s, and an FIS file t hat specifies t he fuzzy infer ence syst em
under consider at ion.
For example, consider an FIS st r uct ur e file named, mam21.fis. We can pr epar e
t he input dat a file using MATLAB:
[x, y] = meshgrid(–5:5, –5:5);
input_data = [x(:) y(:)];
save fis_in input_data –ascii
This saves all t he input dat a as a 121by2 mat r ix in t he ASCII file fis_in,
wher e each r ow of t he mat r ix r epr esent s an input vect or .
Now we can call t he st andalone code:
% fismain fis_in mam21.fis
This gener at es 121 out put s on your scr een. You can dir ect t he out put s t o
anot her file:
% fismain fis_in mam21.fis > fis_out
StandAlone CCode Fuzzy Inference Engine
2131
Now t he file fis_out cont ains a 121by1 mat r ix. In gener al, each r ow of t he
out put mat r ix r epr esent s an out put vect or . The synt ax of fismain is similar t o
it s MEXfile count er par t evalfis.m, except t hat all mat r ices ar e r eplaced wit h
files.
To compar e t he r esult s fr om t he MATLAB MEXfile and t he st andalone
execut able, t ype t he following wit hin MATLAB:
fismat = readfis('mam21');
matlab_out = evalfis(input_data, fismat);
load fis_out
max(max(matlab_out – fis_out))
ans =
4.9583e–13
This t iny differ ence comes fr om t he limit ed lengt h pr int out in t he file fis_out.
Ther e ar e sever al t hings you should know about t his st andalone execut able:
•It is compat ible wit h bot h ANSI and K & R st andar ds for C code, as long as
__STDC__ is defined in ANSI compiler s.
•Cust omized funct ions ar e not allowed in t he st andalone execut able, so you
ar e limit ed t o t he 11 member ship funct ions t hat come wit h t he t oolbox, as
well as ot her fact or y set t ings for AND, OR, IMP, and AGG funct ions.
•fismain.c cont ains only t he main() funct ion and it is heavily document ed
for easy adapt at ion t o ot her applicat ions.
•To add a new member ship funct ion or new r easoning mechanism int o t he
st andalone code, you need t o change t he file fis.c, which cont ains all t he
necessar y funct ions t o per for m t he fuzzy infer ence pr ocess.
•For t he Macint osh, t he compiled command fismain t r ies t o find fismain.in
and fismain.fis as input dat a and FIS descr ipt ion files, r espect ively. The
out put is st or ed in fismain.out. These filenames ar e defined wit hin
Macint oshspecific #define symbols in fismain.c and can be changed if
necessar y.
2 Tutorial
2132
Glossary
This sect ion is designed t o br iefly explain some of t he specialized t er ms t hat ar e
der ived fr om fuzzy logic.
aggregati on  t he combinat ion of t he consequent s of each r ule in a Mamdani
fuzzy infer ence syst em in pr epar at ion for defuzzificat ion.
Adapt i ve NeuroFuzzy Infe rence Sys t em (ANFIS)  a t echnique for
aut omat ically t uning Sugenot ype infer ence syst ems based on t r aining dat a.
antecedent  t he init ial (or “if”) par t of a fuzzy r ule.
cons eque nt  t he final (or “t hen”) par t of a fuzzy r ule.
de fuzzi fi cati on  t he pr ocess of t r ansfor ming a fuzzy out put of a fuzzy
infer ence syst em int o a cr isp out put .
de gree of membe rshi p  t he out put of a member ship funct ion, t his value is
always limit ed t o bet ween 0 and 1. Also known as a member ship value or
member ship gr ade.
de gree of fulfi llment  see fi ri ng s trength.
fi ri ng s tre ngth  t he degr ee t o which t he ant ecedent par t of a fuzzy r ule is
sat isfied. The fir ing st r engt h may be t he r esult of an AND or an OR oper at ion,
and it shapes t he out put funct ion for t he r ule. Also known as degr ee of
fulfillment .
fuzzi fi cati on  t he pr ocess of gener at ing member ship values for a fuzzy
var iable using member ship funct ions.
fuzzy cmeans clus te ri ng  a dat a clust er ing t echnique wher ein each dat a
point belongs t o a clust er t o a degr ee specified by a member ship gr ade.
fuzzy i nfe rence system (FIS)  t he over all name for a syst em t hat uses fuzzy
r easoning t o map an input space t o an out put space.
fuzzy operators  AND, OR, and NOT oper at or s. These ar e also known as
logical connect ives.
fuzzy s et  a set which can cont ain element s wit h only a par t ial degr ee of
member ship.
fuzzy s i ngleton  a fuzzy set wit h a member ship funct ion t hat is unit y at a one
par t icular point and zer o ever ywher e else.
Glossary
2133
i mpli cati on  t he pr ocess of shaping t he fuzzy set in t he consequent based on
t he r esult s of t he ant ecedent in a Mamdanit ype FIS.
Mamdani type i nference  a t ype of fuzzy infer ence in which t he fuzzy set s
fr om t he consequent of each r ule ar e combined t hr ough t he aggr egat ion
oper at or and t he r esult ing fuzzy set is defuzzified t o yield t he out put of t he
syst em.
me mbers hi p functi on (MF)  a funct ion t hat specifies t he degr ee t o which a
given input belongs t o a set or is r elat ed t o a concept .
s i ngle ton output functi on  an out put funct ion t hat is given by a spike at a
single number r at her t han a cont inuous cur ve. In t he Fuzzy Logic Toolbox it is
only suppor t ed as par t of a zer oor der Sugeno model.
subtracti ve clusteri ng  a t echnique for aut omat ically gener at ing fuzzy
infer ence syst ems by det ect ing clust er s in input out put t r aining dat a.
Suge notype i nference  a t ype of fuzzy infer ence in which t he consequent of
each r ule is a linear combinat ion of t he input s. The out put is a weight ed linear
combinat ion of t he consequent s.
Tconorm  (also known as Snor m) a t woinput funct ion t hat descr ibes a
super set of fuzzy union (OR) oper at or s, including maximum, algebr aic sum,
and any of sever al par amet er ized Tconor ms.
Tnorm  a t woinput funct ion t hat descr ibes a super set of fuzzy int er sect ion
(AND) oper at or s, including minimum, algebr aic pr oduct , and any of sever al
par amet er ized Tnor ms.
2 Tutorial
2134
References
[Bez81] Bezdek, J .C., Pattern Recognition with Fuzzy Objective Function
Algorithms, Plenum Pr ess, New Yor k, 1981.
[Chi94] Chiu, S., “Fuzzy Model Ident ificat ion Based on Clust er Est imat ion,”
J ournal of Intelligent & Fuzzy S ystems, Vol. 2, No. 3, Sept . 1994.
[Dub80] Dubois, D. and H. Pr ade, Fuzzy S ets and S ystems: Theory and
Applications, Academic Pr ess, New Yor k, 1980.
[J an91] J ang, J .S. R., “Fuzzy Modeling Using Gener alized Neur al Net wor ks
and Kalman Filt er Algor it hm,” Proc. of the Ninth National Conf. on Artificial
Intelligence (AAAI91), pp. 762767, J uly 1991.
[J an93] J ang, J .S. R., “ANFIS: Adapt iveNet wor kbased Fuzzy Infer ence
Syst ems,” IEEE Transactions on S ystems, Man, and Cybernetics, Vol. 23, No.
3, pp. 665685, May 1993.
[J an94] J ang, J .S. R. and N. Gulley, “Gain scheduling based fuzzy cont r oller
design,” Proc. of the International J oint Conference of the North American
Fuzzy Information Processing S ociety Biannual Conference, the Industrial
Fuzzy Control and Intelligent S ystems Conference, and the NAS A J oint
Technology Workshop on Neural Networks and Fuzzy Logic, San Ant onio,
Texas, Dec. 1994.
[J an95] J ang, J .S. R. and C.T. Sun, “Neur ofuzzy modeling and cont r ol,”
Proceedings of the IEEE, Mar ch 1995.
[J an97] J ang, J .S. R. and C.T. Sun, NeuroFuzzy and S oft Computing: A
Computational Approach to Learning and Machine Intelligence, Pr ent ice Hall,
1997.
[Kau85] Kaufmann, A. and M.M. Gupt a, Introduction to Fuzzy Arithmetic, V.N.
Reinhold, 1985.
[Lee90] Lee, C.C., “Fuzzy logic in cont r ol syst ems: fuzzy logic cont r oller par t s
1 and 2,” IEEE Transactions on S ystems, Man, and Cybernetics, Vol. 20, No. 2,
pp 404435, 1990.
[Mam75] Mamdani, E.H. and S. Assilian, “An exper iment in linguist ic
synt hesis wit h a fuzzy logic cont r oller ,” International J ournal of ManMachine
S tudies, Vol. 7, No. 1, pp. 113, 1975.
References
2135
[Mam76] Mamdani, E.H., “Advances in t he linguist ic synt hesis of fuzzy
cont r oller s,” International J ournal of ManMachine S tudies, Vol. 8, pp.
669678, 1976.
[Mam77] Mamdani, E.H., “Applicat ions of fuzzy logic t o appr oximat e r easoning
using linguist ic synt hesis,” IEEE Transactions on Computers, Vol. 26, No. 12,
pp. 11821191, 1977.
[Sch63] Schweizer , B. and A. Sklar , “Associat ive funct ions and abst r act
semigr oups,” Publ. Math Debrecen, 10:6981, 1963.
[Sug77] Sugeno, M., “Fuzzy measur es and fuzzy int egr als: a sur vey,” (M.M.
Gupt a, G. N. Sar idis, and B.R. Gaines, edit or s) Fuzzy Automata and Decision
Processes, pp. 89102, Nor t hHolland, New Yor k, 1977.
[Sug85] Sugeno, M., Industrial applications of fuzzy control, Elsevier Science
Pub. Co., 1985.
[Wan94] Wang, L.X., Adaptive fuzzy systems and control: design and stability
analysis, Pr ent ice Hall, 1994.
[WidS85] Widr ow, B. and D. St ear ns, Adaptive S ignal Processing, Pr ent ice
Hall, 1985.
[Yag80] Yager , R., “On a gener al class of fuzzy connect ives,” Fuzzy S ets and
S ystems, 4:235242, 1980.
[Yag94] Yager , R. and D. Filev, “Gener at ion of Fuzzy Rules by Mount ain
Clust er ing,” J ournal of Intelligent & Fuzzy S ystems, Vol. 2, No. 3, pp. 209219,
1994.
[Zad65] Zadeh, L.A., “Fuzzy set s,” Information and Control, Vol. 8, pp. 338353,
1965.
[Zad73] Zadeh, L.A., “Out line of a new appr oach t o t he analysis of complex
syst ems and decision pr ocesses,” IEEE Transactions on S ystems, Man, and
Cybernetics, Vol. 3, No. 1, pp. 2844, J an. 1973.
[Zad75] Zadeh, L.A., “The concept of a linguist ic var iable and it s applicat ion t o
appr oximat e r easoning, Par t s 1, 2, and 3,” Information S ciences, 1975,
8:199249, 8:301357, 9:4380
[Zad88] Zadeh, L.A., “Fuzzy Logic,” Computer, Vol. 1, No. 4, pp. 8393, 1988.
[Zad89] Zadeh, L.A., “Knowledge r epr esent at ion in fuzzy logic,” IEEE
Transactions on Knowledge and Data Engineering, Vol. 1, pp. 89100, 1989.
2 Tutorial
2136
3
Refer ence
GUI Tools . . . . . . . . . . . . . . . . . . . . . . 32
Member ship Funct ions . . . . . . . . . . . . . . . . 32
FIS Dat a St r uct ur e Management . . . . . . . . . . . . 33
Advanced Techniques . . . . . . . . . . . . . . . . . 34
Simulink Blocks . . . . . . . . . . . . . . . . . . . 34
Demos . . . . . . . . . . . . . . . . . . . . . . . 35
3 Reference
32
This sect ion of t he chapt er cont ains br ief descr ipt ions of all t he funct ions in t he
Fuzzy Logic Toolbox. The following t ables cont ain t he funct ions list ed by t opic.
GUI Tools
Membership Functions
Function Purpose
anfisedit ANFIS Edit or GUI.
fuzzy Basic FIS Edit or.
mfedit Member ship Funct ion Edit or.
ruleedit Rule Edit or and par ser.
ruleview Rule Viewer and fuzzy infer ence diagr am.
surfview Out put Sur face Viewer.
Function Purpose
dsigmf Differ ence of t wo sigmoid member ship funct ions.
gauss2mf Twosided Gaussian cur ve member ship funct ion.
gaussmf Gaussian cur ve member ship funct ion.
gbellmf Gener alized bell cur ve member ship funct ion.
pimf Pishaped cur ve member ship funct ion.
33
FIS Data Structure Management
psigmf Pr oduct of t wo sigmoidal member ship funct ions.
smf Sshaped cur ve member ship funct ion.
sigmf Sigmoid cur ve member ship funct ion.
trapmf Tr apezoidal member ship funct ion.
trimf Tr iangular member ship funct ion.
zmf Zshaped cur ve member ship funct ion.
Function Purpose
addmf Add member ship funct ion t o FIS.
addrule Add r ule t o FIS.
addvar Add var iable t o FIS.
defuzz Defuzzify member ship funct ion.
evalfis Per for m fuzzy infer ence calculat ion.
evalmf Gener ic member ship funct ion evaluat ion.
gensurf Gener at e FIS out put sur face.
getfis Get fuzzy syst em pr oper t ies.
mf2mf Tr anslat e par amet er s bet ween funct ions.
newfis Cr eat e new FIS.
parsrule Par se fuzzy r ules.
plotfis Display FIS input out put st r uct ur e.
plotmf Plot all of t he member ship funct ions associat ed
wit h a given var iable.
Function Purpose
3 Reference
34
Advanced Techniques
Simulink Blocks
readfis Load FIS fr om disk.
rmmf Remove member ship funct ion fr om FIS.
rmvar Remove var iable fr om FIS.
setfis Set fuzzy syst em pr oper t ies.
showfis Display annot at ed FIS.
showrule Display FIS r ules.
writefis Save FIS t o disk.
Function Purpose
anfis Tr aining r out ine for a Sugenot ype FIS (MEX only).
fcm Find clust er s wit h FCM clust er ing.
genfis1 Gener at e FIS mat r ix using gr id met hod.
genfis2 Gener at e FIS mat r ix using subt r act ive clust er ing.
subclust Find clust er cent er s wit h subt r act ive clust er ing.
Function Purpose
fuzblock Fuzzy logic cont r oller blocks and demo blocks.
sffis Fuzzy infer ence Sfunct ion.
Function Purpose
35
Demos
Function Purpose
defuzzdm Defuzzificat ion met hods.
fcmdemo FCM clust er ing demo (2D).
fuzdemos GUI for Fuzzy Logic Toolbox demos.
gasdemo ANFIS demo for fuel efficiency using subclust er ing.
juggler Balljuggler wit h Rule Viewer.
invkine Inver se kinemat ics of a r obot ar m.
irisfcm FCM clust er ing demo (4D).
noisedm Adapt ive noise cancellat ion.
slbb Ball and beam cont r ol (Simulink ).
slcp Inver t ed pendulum cont r ol (Simulink ).
sltank Wat er level cont r ol (Simulink).
sltankrule Wat er level cont r ol wit h Rule Viewer (Simulink).
sltbu Tr uck backerupper (Simulink only).
addmf
36
3addmf
Purpose Add a member ship funct ion t o an FIS.
Synopsis a = addmf(a,'varType',varIndex,'mfName','mfType',mfParams)
Description A member ship funct ion can only be added t o a var iable in an exist ing MATLAB
wor kspace FIS. Indices ar e assigned t o member ship funct ions in t he or der in
which t hey ar e added, so t he fir st member ship funct ion added t o a var iable will
always be known as member ship funct ion number one for t hat var iable. You
cannot add a member ship funct ion t o input var iable number t wo of a syst em if
only one input has been defined.
The funct ion r equir es six input ar gument s in t his or der :
1 A MATLAB var iable name of a FIS st r uct ur e in t he wor kspace
2 A st r ing r epr esent ing t he t ype of var iable you want t o add t he member ship
funct ion t o ('input' or 'output')
3 The index of t he var iable you want t o add t he member ship funct ion t o
4 A st r ing r epr esent ing t he name of t he new member ship funct ion
5 A st r ing r epr esent ing t he t ype of t he new member ship funct ion
6 The vect or of par amet er s t hat specify t he member ship funct ion
addmf
37
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
38
3addr ule
Purpose Add a r ule t o an FIS.
Synopsis a = addrule(a,ruleList)
Description addrule has t wo ar gument s. The fir st ar gument is t he MATLAB wor kspace
var iable FIS name. The second ar gument for addrule is a mat r ix of one or mor e
r ows, each of which r epr esent s a given r ule. The for mat t hat t he r ule list mat r ix
must t ake is ver y specific. If t her e ar e m input s t o a syst em and n out put s, t her e
must be exact ly m + n + 2 columns t o t he r ule list .
The fir st m columns r efer t o t he input s of t he syst em. Each column cont ains a
number t hat r efer s t o t he index of t he member ship funct ion for t hat var iable.
The next n columns r efer t o t he out put s of t he syst em. Each column cont ains a
number t hat r efer s t o t he index of t he member ship funct ion for t hat var iable.
The m + n + 1 column cont ains t he weight t hat is t o be applied t o t he r ule. The
weight must be a number bet ween zer o and one, and is gener ally left as one.
The m + n + 2 column cont ains a 1 if t he fuzzy oper at or for t he r ule’s ant ecedent
is AND. It cont ains a 2 if t he fuzzy oper at or is OR.
Example ruleList=[
1 1 1 1 1
1 2 2 1 1];
a = addrule(a,ruleList);
If t he above syst em a has t wo input s and one out put , t he fir st r ule can be
int er pr et ed as: “If input 1 is MF 1 and input 2 is MF 1, t hen out put 1 is MF 1.”
See Also addmf, addvar, rmmf, rmvar, parsrule, showrule
addvar
39
3addvar
Purpose Add a var iable t o an FIS.
Synopsis a = addvar(a,'varType','varName',varBounds)
Description addvar has four ar gument s in t his or der :
1 The name of a FIS st r uct ur e in t he MATLAB wor kspace
2 A st r ing r epr esent ing t he t ype of t he var iable you want t o add ('input' or
'output')
3 A st r ing r epr esent ing t he name of t he var iable you want t o add
4 The vect or descr ibing t he limit ing r ange values for t he var iable you want t o
add
Indices ar e applied t o var iables in t he or der in which t hey ar e added, so t he
fir st input var iable added t o a syst em will always be known as input var iable
number one for t hat syst em. Input and out put var iables ar e number ed
independent ly.
Example a=newfis('tipper');
a=addvar(a,'input','service',[0 10]);
getfis(a,'input',1)
MATLAB r eplies
Name = service
NumMFs = 0
MFLabels =
Range = [0 10]
See Also addmf, addrule, rmmf, rmvar
anfis
310
3anfis
Purpose Tr aining r out ine for Sugenot ype FIS (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 t he major t r aining r out ine for Sugenot ype fuzzy infer ence syst ems.
anfis uses a hybr id lear ning algor it hm t o ident ify par amet er s of Sugenot ype
fuzzy infer ence syst ems. It applies a combinat ion of t he least squar es met hod
and t he backpr opagat ion gr adient descent met hod for t r aining FIS
member ship funct ion par amet er s t o emulat e a given t r aining dat a set . anfis
can also be invoked using an opt ional ar gument for model validat ion. The t ype
of model validat ion t hat t akes place wit h t his opt ion is a checking for model
over fit t ing, and t he ar gument is a dat a set called t he checking dat a set .
The ar gument s in t he above descr ipt ion for anfis ar e as follows:
•trnData: t he name of a t r aining dat a set . This is a mat r ix wit h all but t he
last column cont aining input dat a, while t he last column cont ains a single
vect or of out put dat a.
•fismat: t he name of an FIS, (fuzzy infer ence syst em) used t o pr ovide anfis
wit h an init ial set of member ship funct ions for t r aining. Wit hout t his opt ion,
anfis will use genfis1 t o implement a default init ial FIS for t r aining. This
default FIS will have t wo member ship funct ions of t he Gaussian t ype, when
invoked wit h only one ar gument . If fismat is pr ovided as a single number (or
a vect or ), it is t aken as t he number of member ship funct ions (or t he vect or
whose ent r ies ar e t he r espect ive number s of member ship funct ions
associat ed wit h each r espect ive input when t hese number s differ for each
input ). In t his case, bot h ar gument s of anfis ar e passed t o genfis1 t o
gener at e a valid FIS st r uct ur e befor e st ar t ing t he t r aining pr ocess.
anfis
311
•trnOpt: vect or of t r aining opt ions. When any t r aining opt ion is ent er ed as
NaN t he default opt ions will be in for ce. These opt ions ar e as follows:
trnOpt(1): t r aining epoch number (default : 10)
trnOpt(2): t r aining er r or goal (default : 0)
trnOpt(3): init ial st ep size (default : 0.01)
trnOpt(4): st ep size decr ease r at e (default : 0.9)
trnOpt(5): st ep size incr ease r at e (default : 1.1)
•dispOpt: vect or of display opt ions t hat specify what message t o display in t he
MATLAB command window dur ing t r aining. The default value for any
display opt ion is 1, which means t he cor r esponding infor mat ion is displayed.
A 0 means t he cor r esponding infor mat ion is not displayed on t he scr een.
When any display opt ion is ent er ed as NaN, t he default opt ions will be in
for ce. These opt ions ar e as follows:
dispOpt(1): ANFIS infor mat ion, such as number s of input and out put
member ship funct ions, and so on (default : 1)
dispOpt(2): er r or (default : 1)
dispOpt(3): st ep size at each par amet er updat e (default : 1)
dispOpt(4): final r esult s (default : 1)
•chkData: t he name of an opt ional checking dat a set for over fit t ing model
validat ion. This dat a set is a mat r ix in t he same for mat as t he t r aining dat a
set .
•optMethod: opt ional opt imizat ion met hod used in member ship funct ion
par amet er t r aining: eit her 1 for t he hybr id met hod or 0 for t he
backpr opagat ion met hod. The default met hod is t he hybr id met hod, which is
a combinat ion of least squar es est imat ion wit h backpr opagat ion. The default
met hod is invoked whenever t he ent r y for t his ar gument is anyt hing but 0.
The t r aining pr ocess st ops whenever t he designat ed epoch number is r eached
or t he t r aining er r or goal is achieved.
anfis
312
Note on anfis arguments: When anfis is invoked wit h t wo or mor e
ar gument s, any opt ional ar gument s will t ake on t heir default values if t hey
ar e ent er ed as NaNs or empt y mat r ices. Default values can be changed dir ect ly
by modifying t he file anfis.m. Eit her NaNs or empt y mat r ices must be used as
placeholder s for var iables if you don’t want t o specify t hem, but do want t o
specify succeeding ar gument s, for example, when you implement t he checking
dat a opt ion of anfis.
The r ange var iables in t he above descr ipt ion for anfis ar e as follows:
•fismat1 is t he FIS st r uct ur e whose par amet er s ar e set accor ding t o a
minimum t r aining er r or cr it er ion.
•error1 or error2 is an ar r ay of r oot mean squar ed er r or s r epr esent ing t he
t r aining dat a er r or signal and t he checking dat a er r or signal, r espect ively.
•stepsize is an ar r ay of st ep sizes. The st ep size is decr eased (by mult iplying
it wit h t he component of t he t r aining opt ion cor r esponding t o t he st ep size
decr ease r at e) if t he er r or measur e under goes t wo consecut ive combinat ions
of an incr ease followed by a decr ease. The st ep size is incr eased (by
mult iplying it wit h t he incr ease r at e) if t he er r or measur e under goes four
consecut ive decr eases.
•fismat2 is t he FIS st r uct ur e whose par amet er s ar e set accor ding t o a
minimum checking er r or cr it er ion.
anfis
313
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 Modeling Using Gener alized Neur al Net wor ks and
Kalman Filt er Algor it hm,” Proc. of the Ninth National Conf. on Artificial
Intelligence (AAAI91), pp. 762767, J uly 1991.
J ang, J .S. R., “ANFIS: Adapt iveNet wor kbased Fuzzy Infer ence Syst ems,”
IEEE Transactions on S ystems, Man, and Cybernetics, Vol. 23, No. 3, pp.
665685, May 1993.
anfisedit
314
3anfisedit
Purpose To open t he ANFIS Edit or GUI.
Synopsis anfisedit('a')
anfisedit(a)
anfisedit
Description
Using anfisedit, you br ing up t he ANFIS Edit or GUI fr om which you can load
a dat a set and t r ain anfis. The ANFIS Edit or 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 Dat a 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
315
anfisedit('a'), br ings up t he ANFIS Edit or GUI fr om which you can
implement anfis using a FIS st r uct ur e st or ed as a file on your disk called,
a.fis.
anfisedit(a) oper at es t he same way for a FIS st r uct ur e a, st or ed as a var iable
in t he MATLAB wor kspace.
Refer t o “anfis and t he ANFIS Edit or GUI” on page 292 for mor e infor mat ion
about how t o use anfisedit.
Menu Items On t he ANFIS Edit or GUI, t her e is a menu bar t hat allows you t o open r elat ed
GUI t ools, open and save syst ems, and so on. The Fi le menu is t he same as t he
one found on t he FIS Edit or . Refer t o fuzzy on page 329 for mor e infor mat ion.
•Use t he following Edi t menu it em:
Undo t o undo t he most r ecent change.
•Use t he following Vi e w menu it ems:
Edi t FIS properti e s... t o invoke t he FIS Edit or .
Edi t rule s... t o invoke t he Rule Edit or .
Edi t members hi p functi ons ... t o invoke t he Member ship Funct ion Edit or .
Vi e w rules ... t o invoke t he Rule Viewer .
Vi e w surface ... t o invoke t he Sur face Viewer .
See Also fuzzy, mfedit, ruleedit, ruleview, surfview
convertfis
316
3conver t fis
Purpose Conver t a Fuzzy Logic Toolbox ver sion 1.0 FIS mat r ix t o a ver sion 2.0 FIS
st r uct ur e.
Synopsis fis_new=convertfis(fis_old)
Description convertfis t akes a ver sion 1.0 FIS mat r ix and conver t s it t o a ver sion 2.0
st r uct ur e.
defuzz
317
3defuzz
Purpose Defuzzify member ship funct ion.
Synopsis out = defuzz(x,mf,type)
Description defuzz(x,mf,type) r et ur ns a defuzzified value out, of a member ship funct ion
mf posit ioned at associat ed var iable value x, using one of sever al defuzzificat ion
st r at egies, accor ding t o t he ar gument , type. The var iable type can be one of t he
following.
•centroid: cent r oid of ar ea met hod
•bisector: bisect or of ar ea met hod
•mom: mean of maximum met hod
•som: smallest of maximum met hod
•lom: lar gest of maximum met hod
If type is not one of t he above, it is assumed t o be a user defined funct ion. x and
mf ar e passed t o t his funct ion t o gener at e t he defuzzified out put .
Examples x = −10:0.1:10;
mf = trapmf(x,[−10 −8 −4 7]);
xx = defuzz(x,mf,'centroid');
dsigmf
318
3dsigmf
Purpose Built in member ship funct ion composed of t he differ ence bet ween t wo
sigmoidal member ship funct ions.
Synopsis y = dsigmf(x,[a1 c1 a2 c2])
Description The sigmoidal member ship funct ion used her e depends on t he t wo par amet er s
a and c and is given by
The member ship funct ion dsigmf depends on four par amet er s, a1, c1, a2, and
c2, and is t he differ ence bet ween t wo of t hese sigmoidal funct ions:
f
1
(x; a1, c
1
)  f
2
(x; a2, c
2
)
The par amet er s ar e list ed in t he or der : [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
319
3evalfis
Purpose Per for m fuzzy infer ence calculat ions.
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 t he following ar gument s:
•input: a number or a mat r ix specifying input values. If input is an MbyN
mat r ix, wher e N is number of input var iables, t hen evalfis t akes each r ow
of input as an input vect or and r et ur ns t he MbyL mat r ix t o t he var iable,
output, wher e each r ow is an out put vect or and L is t he number of out put
var iables.
•fismat: an FIS st r uct ur e t o be evaluat ed.
•numPt s: an opt ional ar gument t hat r epr esent s t he number of sample point s
on which t o evaluat e t he member ship funct ions over t he input or out put
r ange. If t his ar gument is not used, t he default value of 101 point is used.
The r ange labels for evalfis ar e as follows:
•output: t he out put mat r ix of size MbyL, wher e M r epr esent s t he number of
input values specified above, and L is t he number of out put var iables for t he
FIS.
The opt ional r ange var iables for evalfis ar e only calculat ed when t he input
ar gument is a r ow vect or , (only one set of input s is applied). These opt ional
r ange var iables ar e:
•IRR: t he r esult of evaluat ing t he input values t hr ough t he member ship
funct ions. This is a mat r ix of size numRulesbyN, wher e numRules is t he
number of r ules, and N is t he number of input var iables.
•ORR: t he r esult of evaluat ing t he out put values t hr ough t he member ship
funct ions. This is a mat r ix of size numPtsbynumRules*L, wher e numRules
is t he number of r ules, and L is t he number of out put s. The fir st numRules
columns of t his mat r ix cor r espond t o t he fir st out put , t he next numRules
columns of t his mat r ix cor r espond t o t he second out put , and so for t h.
•ARR: t he numPtsbyL mat r ix of t he aggr egat e values sampled at numPts along
t he out put r ange for each out put .
evalfis
320
When invoked wit h only one r ange var iable, t his funct ion comput es t he out put
vect or , output, of t he fuzzy infer ence syst em specified by t he st r uct ur e,
fismat, for t he input value specified by t he number or mat r ix, input.
Example fismat = readfis('tipper');
out = evalfis([2 1; 4 9],fismat)
This gener at es t he r esponse
out =
7.0169
19.6810
See Also ruleview, gensurf
evalmf
321
3evalmf
Purpose Gener ic member ship funct ion evaluat ion.
Synopsis y = evalmf(x,mfParams,mfType)
Description evalmf evaluat es any member ship funct ion, wher e x is t he var iable r ange for
t he member ship funct ion evaluat ion, mfType is a member ship funct ion fr om
t he t oolbox, and mfParams ar e appr opr iat e par amet er s for t hat funct ion.
If you want t o cr eat e your own cust om member ship funct ion, evalmf will st ill
wor k, because it evaluat es any member ship funct ion whose name it doesn’t
r ecognize.
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
322
3fcm
Purpose Fuzzy cmeans clust er ing.
Synopsis [center,U,obj_fcn] = fcm(data,cluster_n)
Description [center, U, obj_fcn] = fcm(data, cluster_n) applies t he fuzzy cmeans
clust er ing met hod t o a given dat a set .
The input ar gument s of t his funct ion ar e:
•data: dat a set t o be clust er ed; each r ow is a sample dat a point
•cluster_n: number of clust er s (gr eat er t han one)
The out put ar gument s of t his funct ion ar e:
•center: mat r ix of final clust er cent er s wher e each r ow pr ovides t he cent er
coor dinat es
•U: final fuzzy par t it ion mat r ix (or member ship funct ion mat r ix)
•obj_fcn: values of t he object ive funct ion dur ing it er at ions
fcm(data,cluster_n,options) uses an addit ional ar gument var iable,
options, t o cont r ol clust er ing par amet er s, int r oduce a st opping cr it er ia, and/
or set t he it er at ion infor mat ion display:
options(1): exponent for t he par t it ion mat r ix U (default : 2.0)
options(2): maximum number of it er at ions (default : 100)
options(3): minimum amount of impr ovement (default : 1e5)
options(4): info display dur ing it er at ion (default : 1)
If any ent r y of options is NaN, t he default value for t hat opt ion is used inst ead.
The clust er ing pr ocess st ops when t he maximum number of it er at ions is
r eached, or when t he object ive funct ion impr ovement bet ween t wo consecut ive
it er at ions is less t han t he minimum amount of impr ovement specified.
fcm
323
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
324
3findclust er
Purpose Int er act ive clust er ing GUI for fuzzy cmeans and subclust er ing.
Synopsis findcluster
findcluster('file.dat')
Description findcluster br ings up a GUI t o implement fuzzy cmeans (fcm) and/or fuzzy
subt r act ive clust er ing (subtracti v) using t he pulldown t ab under Method on
t he GUI. Dat a is ent er ed using t he Load Data but t on. The opt ions for each of
t hese met hods ar e set t o default values. These can be changed. A descr ipt ion of
t he opt ions for fuzzy cmeans is found in fcm on page 322. A descr ipt ion of t he
opt ions for fuzzy subclust er ing is found in subclust on page 372.
This t ool wor ks on mult idimensional dat a set s, but only displays t wo of t hose
dimensions. Use t he pulldown t abs under Xaxi s and Yaxi s t o select which
dat a dimension you want t o view. For example, if you have dat a t hat is
fivedimensional, t his t ool labels t he dat a as data_1, data_2, data_3, data_4,
data_5, in t he or der in which t he dat a appear s in t he dat a set . Start will
per for m t he clust er ing, and Save Ce nter will save t he clust er cent er .
When oper at ing on a dat a set , file.dat, findcluster (file.dat) loads t he
dat a set aut omat ically, plot t ing up t o t he fir st t wo dimensions of t he dat a only.
findcluster
325
You can st ill choose which t wo dimensions of t he dat a you want t o clust er aft er
t he GUI comes up.
Example findcluster('clusterdemo.dat')
See Also fcm, subclust
fuzarith
326
3fuzarit h
Purpose To per for m fuzzy ar it hmet ic.
Synopsis C = fuzarith(X, A, B, operator)
Description Using int er val ar it hmet ic, C = fuzarith(X, A, B, operator) r et ur ns a fuzzy set
C as t he r esult of applying t he funct ion r epr esent ed by t he st r ing, operator,
t hat per for ms a binar y oper at ion on t he sampled convex fuzzy set s A and B. The
element s of A and B ar e der ived fr om convex funct ions of t he sampled univer se,
X.
•A, B, and X ar e vect or s of t he same dimension.
•operator is one of t he following st r ings: 'sum', 'sub', 'prod', and 'div'.
•The r et ur ned fuzzy set C is a column vect or wit h t he same lengt h as X.
Remark Fuzzy addit ion might gener at e t he message: divide by zero, but t his will not
affect t he cor r ect ness of t his funct ion.
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 AB');
C3 = fuzarith(x, A, B, 'prod');
fuzblock
327
3fuzblock
Purpose Simulink fuzzy logic cont r oller block.
Synopsis fuzblock
Description This command br ings up a Simulink syst em t hat , in addit ion t o some Simulink
demo blocks, cont ains t wo Simulink blocks you can use:
•The Fuzzy Logic Cont r oller
•The Fuzzy Logic Cont r oller Wit h Rule Viewer , (see also ruleview on page
361). This block for ces t he Rule Viewer t o pop open dur ing a Simulink
simulat ion.
The dialog box associat ed wit h eit her of t hese blocks is found by doubleclicking
on t he Fuzzy Logic Cont r oller block. This box cont ains t he name of t he FIS
st r uct ur e in t he wor kspace t hat cor r esponds t o t he desir ed fuzzy syst em you
want in your Simulink model.
To open t his dialog box for t he Fuzzy Logic Cont r oller Wit h Rule Viewer block,
you have t o
1 Doubleclick on t his block, and a Simulink diagr am wit h a Fuzzy Logic
Cont r oller block opens.
2 Doubleclick on t he second Fuzzy Logic Cont r oller block t hat pops open.
If t he fuzzy infer ence syst em has mult iple input s, t hese input s should be
mult iplexed t oget her befor e feeding t hem int o eit her t he Fuzzy Logic
Cont r oller or t he Fuzzy Logic Cont r oller Wit h Rule Viewer block. Similar ly, if
t he syst em has mult iple out put s, t hese signals will be passed out of t he block
on one mult iplexed line.
See Also sffis, ruleview
fuzdemos
328
3fuzdemos
Purpose List of all Fuzzy Logic Toolbox demos.
Synopsis fuzdemos
Description This funct ion br ings up a GUI t hat allows you t o choose bet ween any of sever al
Fuzzy Logic Toolbox demos list ed under “Demos” on page 35.
fuzzy
329
3fuzzy
Purpose To invoke t he basic FIS edit or .
Synopsis fuzzy
fuzzy(fismat)
This GUI t ool allows you t o edit t he highest level feat ur es of t he fuzzy infer ence
syst em, such as t he number of input and out put var iables, t he defuzzificat ion
met hod used, and so on. Refer t o “The FIS Edit or ” on page 249 and ff., for mor e
infor mat ion about how t o use t he GUIs associat ed wit h fuzzy.
The FIS Edit or is t he highlevel display for any fuzzy logic infer ence syst em. It
allows you t o call t he var ious ot her edit or s t o oper at e on t he FIS. This int er face
allows convenient access t o all ot her edit or s wit h an emphasis on maximum
flexibilit y for int er act ion wit h t he fuzzy syst em.
The Diagram The diagr am displayed at t he t op of t he window shows t he input s, out put s, and
a cent r al fuzzy r ule pr ocessor . Click on one of t he var iable boxes t o make t he
select ed box t he cur r ent var iable. You should see t he box highlight ed in r ed.
Doubleclick on one of t he var iables t o br ing up t he Member ship Funct ion
Edit or . Doubleclick on t he fuzzy r ule pr ocessor t o br ing up t he Rule Edit or . If
fuzzy
330
a var iable exist s but is not ment ioned in t he r ule base, it is connect ed t o t he
r ule pr ocessor block wit h a dashed r at her t han a solid line.
Menu Items The FIS Edit or displays a menu bar t hat allows you t o open r elat ed GUI t ools,
open and save syst ems, and so on.
•Under Fi le select :
New Mamdani FIS... t o open a new Mamdanist yle syst em wit h no
var iables and no r ules called Untitled.
New Sugeno FIS... t o open a new Sugenost yle syst em wit h no var iables
and no r ules called Untitled.
Open from di s k... t o load a syst em fr om a specified .fis file on disk.
Save to di s k t o save t he cur r ent syst em t o a .fis file on disk.
Save to di s k as... t o save t he cur r ent syst em t o disk wit h t he opt ion t o
r ename or r elocat e t he file.
Open from works pace... t o load a syst em fr om a specified FIS st r uct ur e
var iable in t he wor kspace.
Save to workspace ... t o save t he syst em t o t he cur r ent ly named FIS
st r uct ur e var iable in t he wor kspace.
Save to workspace as... t o save t he syst em t o a specified FIS st r uct ur e
var iable in t he wor kspace.
Close wi ndow t o close t he GUI.
•Under Edi t select :
Add i nput t o add anot her input t o t he cur r ent syst em.
Add output t o add anot her out put t o t he cur r ent syst em.
Re move vari able t o delet e a select ed var iable.
Undo t o undo t he most r ecent change.
•Under Vi e w select :
Edi t MFs ... t o invoke t he Member ship Funct ion Edit or .
Edi t rules... t o invoke t he Rule Edit or .
Edi t anfi s... t o invoke t he ANFIS Edit or for single out put Sugeno syst ems
only.
Vi e w rules ... t o invoke t he Rule Viewer .
Vi e w surface... t o invoke t he Sur face Viewer .
fuzzy
331
Inference
Method Popup
Menus
Five popup menus ar e pr ovided t o change t he funct ionalit y of t he five basic
st eps in t he fuzzy implicat ion pr ocess:
•And me thod: Choose min, prod, or Custom, for a cust om oper at ion.
•Or me thod: Choose max, probor (pr obabilist ic or ), or Custom, for a cust om
oper at ion.
•Impli cati on me thod: Choose min, prod, or Custom, for a cust om oper at ion.
This select ion is not available for Sugenost yle fuzzy infer ence.
•Aggre gati on method: Choose max, sum, probor, or Custom, for a cust om
oper at ion. This select ion is not available for Sugenost yle fuzzy infer ence.
•De fuzzi fi cati on method: For Mamdanist yle infer ence, choose centroid,
bisector, mom (middle of maximum), som (smallest of maximum), lom
(lar gest of maximum), or Custom, for a cust om oper at ion. For Sugenost yle
infer ence, choose bet ween wtaver (weight ed aver age) or wtsum (weight ed
sum).
See Also mfedit, ruleedit, ruleview, surfview, anfisedit
gauss2mf
332
3gauss2mf
Purpose Gaussian combinat ion member ship funct ion.
Synopsis y = gauss2mf(x,[sig1 c1 sig2 c2])
Description The Gaussian function depends on two parameters sig and c as given by
The funct ion gauss2mf is a combinat ion of t wo of t hese. The fir st funct ion,
specified by sig1 and c1, det er mines t he shape of t he left most cur ve. The second
funct ion specified by sig2 and c2 det er mines t he shape of t he r ight most cur ve.
Whenever c1 < c2, t he gauss2mf funct ion r eaches a maximum value of 1.
Ot her wise, t he maximum value is less t han one. The par amet er s ar e list ed in
t he or der :
[sig1, c1, sig2, c2].
f x σ ; c , ( ) e
x c – ( ) –
2
2σ
2

=
gauss2mf
333
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
334
3gaussmf
Purpose Gaussian cur ve built in member ship funct ion.
Synopsis y = gaussmf(x,[sig c])
Description The symmet r ic Gaussian funct ion depends on t wo par amet er s and c as given
by
The par amet er s for gaussmf r epr esent t he par amet er s and c list ed in or der
in t he vect or [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
335
3gbellmf
Purpose Gener alized bellshaped built in member ship funct ion.
Synopsis y = gbellmf(x,params)
Description The gener alized bell funct ion depends on t hr ee par amet er s a, b, and c as given
by
wher e t he par amet er b is usually posit ive. The par amet er c locat es t he cent er
of t he cur ve. Ent er t he par amet er vect or params, t he second ar gument for
gbellmf, as t he vect or whose ent r ies ar e a, b, and c, r espect ively.
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
336
3genfis1
Purpose Gener at e an FIS st r uct ur e fr om dat a wit hout dat a clust er ing.
Synopsis fismat = genfis1(data)
fismat = genfis1(data,numMFs,inmftype, outmftype)
Description genfis1 gener at es a Sugenot ype FIS st r uct ur e used as init ial condit ions
(init ializat ion of t he member ship funct ion par amet er s) for anfis t r aining.
genfis1(data, numMFs, inmftype, outmftype) gener at es a FIS st r uct ur e fr om a
t r aining dat a set , data, using a gr id par t it ion on t he dat a (no clust er ing).
The ar gument s for genfis1 ar e as follows:
•data is t he t r aining dat a mat r ix, which must be ent er ed wit h all but t he last
columns r epr esent ing input dat a, and t he last column r epr esent ing t he
single out put .
•numMFs is a vect or whose coor dinat es specify t he number of member ship
funct ions associat ed wit h each input . If you want t he same number of
member ship funct ions t o be associat ed wit h each input , t hen it suffices t o
make numMFs a single number .
•inmftype is a st r ing ar r ay in which each r ow specifies t he member ship
funct ion t ype associat ed wit h each input . Again, t his can be a
onedimensional single st r ing if t he t ype of member ship funct ions associat ed
wit h each input is t he same.
•outmftype is a st r ing t hat specifies t he member ship funct ion t ype associat ed
wit h t he out put . Ther e can only be one out put , since t his is a Sugenot ype
syst em. The out put member ship funct ion t ype must be eit her linear or
constant.
The number of member ship funct ions associat ed wit h t he out put is t he same
as t he number of r ules gener at ed by genfis1. The default number of
member ship funct ions, numMFs, is 2; t he default input or out put member ship
funct ion t ype is 'gbellmf'. These ar e used whenever genfis1 is invoked
wit hout t he last t hr ee ar gument s.
genfis1
337
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
338
3genfis2
Purpose Gener at e an FIS st r uct ur e fr om dat a using subt r act ive clust er ing.
Synopsis fismat = genfis2(Xin,Xout,radii)
fismat = genfis2(Xin,Xout,radii,xBounds)
fismat = genfis2(Xin,Xout,radii,xBounds,options)
Description Given separ at e set s of input and out put dat a, genfis2 gener at es an FIS using
fuzzy subt r act ive clust er ing. When t her e is only one out put , genfis2 may be
used t o gener at e an init ial FIS for anfis t r aining by fir st implement ing
subt r act ive clust er ing on t he dat a. genfis2 accomplishes t his by ext r act ing a
set of r ules t hat models t he dat a behavior . The r ule ext r act ion met hod fir st
uses t he subclust funct ion t o det er mine t he number of r ules and ant ecedent
member ship funct ions and t hen uses linear least squar es est imat ion t o
det er mine each r ule’s consequent equat ions. This funct ion r et ur ns an FIS
st r uct ur e t hat cont ains a set of fuzzy r ules t o cover t he feat ur e space.
The ar gument s for genfis2 ar e as follows:
•Xin is a mat r ix in which each r ow cont ains t he input values of a dat a point .
•Xout is a mat r ix in which each r ow cont ains t he out put values of a dat a point .
•radii is a vect or t hat specifies a clust er cent er ’s r ange of influence in each of
t he dat a dimensions, assuming t he dat a falls wit hin a unit hyper box. For
example, if t he dat a dimension is 3 (e.g., Xin has t wo columns and Xout has
one column), radii = [0.5 0.4 0.3] specifies t hat t he r anges of influence in t he
fir st , second, and t hir d dat a dimensions (i.e., t he fir st column of Xin, t he
second column of Xin, and t he column of Xout) ar e 0.5, 0.4, and 0.3 t imes t he
widt h of t he dat a space, r espect ively. If radii is a scalar , t hen t he scalar
value is applied t o all dat a dimensions, i.e., each clust er cent er will have a
spher ical neighbor hood of influence wit h t he given r adius.
•xBounds is a 2byN opt ional mat r ix t hat specifies how t o map t he dat a in Xin
and Xout int o a unit hyper box, wher e N is t he dat a (r ow) dimension. The fir st
r ow of xBounds cont ains t he minimum axis r ange values and t he second r ow
cont ains t he maximum axis r ange values for scaling t he dat a in each
dimension. For example, xBounds = [10 0 1; 10 50 1] specifies t hat dat a
values in t he fir st dat a dimension ar e t o be scaled fr om t he r ange [10 +10]
int o values in t he r ange [0 1]; dat a values in t he second dat a dimension ar e
t o be scaled fr om t he r ange [0 50]; and dat a values in t he t hir d dat a
genfis2
339
dimension ar e t o be scaled fr om t he r ange [1 +1]. If xBounds is an empt y
mat r ix or not pr ovided, t hen xBounds default s t o t he minimum and
maximum dat a values found in each dat a dimension.
•options is an opt ional vect or for specifying algor it hm par amet er s t o over r ide
t he default values. These par amet er s ar e explained in t he help t ext for
subclust on page 372. Default values ar e in place when t his ar gument is not
specified.
Examples fismat = genfis2(Xin,Xout,0.5)
This is t he minimum number of ar gument s needed t o use t his funct ion. Her e a
r ange of influence of 0.5 is specified for all dat a dimensions.
fismat = genfis2(Xin,Xout,[0.5 0.25 0.3])
This assumes t he combined dat a dimension is 3. Suppose Xin has t wo columns
and Xout has one column, t hen 0.5 and 0.25 ar e t he r anges of influence for each
of t he Xin dat a dimensions, and 0.3 is t he r ange of influence for t he Xout dat a
dimension.
fismat = genfis2(Xin,Xout,0.5,[10 5 0; 10 5 20])
This specifies how t o nor malize t he dat a in Xin and Xout int o values in t he
r ange [0 1] for pr ocessing. Suppose Xin has t wo columns and Xout has one
column, t hen t he dat a in t he fir st column of Xin ar e scaled fr om [10 +10], t he
dat a in t he second column of Xin ar e scaled fr om [5 +5], and t he dat a in Xout
ar e scaled fr om [0 20].
See Also subclust
gensurf
340
3gensur f
Purpose Gener at e an FIS out put sur face.
Synopsis gensurf(fis)
gensurf(fis,inputs,output)
gensurf(fis,inputs,output,grids,refinput)
Description gensurf(fis) gener at es a plot of t he out put sur face of a given fuzzy infer ence
syst em (fis) using t he fir st t wo input s and t he fir st out put .
gensurf(fis,inputs,output) gener at es a plot using t he input s (one or t wo)
and out put (only one is allowed) given, r espect ively, by t he vect or , inputs, and
t he scalar , output.
gensurf(fis,inputs,output,grids) allows you t o specify t he number of gr ids
in t he X (fir st , hor izont al) and Y (second, ver t ical) dir ect ions. If grids is a t wo
element vect or , t he gr ids in t he X and Y dir ect ions can be set independent ly.
gensurf(fis,inputs,output,grids,refinput) can be used if t her e ar e mor e
t han t wo out put s. The lengt h of t he vect or refinput is t he same as t he number
of input s.
•Ent er NaNs for t he ent r ies of refinput cor r esponding t o t he input s whose
sur face is being displayed.
•Ent er r eal double scalar s t o fix t he values of ot her input s.
[x,y,z]=gensurf(...) r et ur ns t he var iables t hat define t he out put sur face
and suppr esses aut omat ic plot t ing.
gensurf
341
Example 1 a = readfis('tipper');
gensurf(a)
Example 2 a = gensurf(Temp,[1 2],1,[20 20],[nan nan 0.2]);
gener at es t he sur face of a t hr eeinput FIS named Temp fr om it s fir st t wo input s
t o it s fir st out put , while fixing a r efer ence value for t he t hir d 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
342
3get fis
Purpose Get fuzzy syst em pr oper t ies.
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 t he fundament al access funct ion for t he FIS st r uct ur e. Wit h t his one
funct ion you can lear n about ever y par t of t he fuzzy infer ence syst em.
The ar gument s for getfis ar e as follows:
•a: t he name of a wor kspace var iable FIS st r uct ur e.
•'vartype': a st r ing indicat ing t he t ype of var iable you want (input or
output).
•varindex: an int eger indicat ing t he index of t he var iable you want (1, for
input 1, for example).
•'mf': a r equir ed st r ing t hat indicat es you ar e sear ching for member ship
funct ion infor mat ion.
•mfindex: t he index of t he member ship funct ion for which you ar e seeking
infor mat ion.
getfis
343
Examples One input ar gument (out put is t he empt y 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
Two input ar gument s
getfis(a,'type')
ans =
mamdani
Thr ee input ar gument s (out put is t he empt y set )
getfis(a,'input',1)
Name = service
NumMFs = 3
MFLabels =
poor
good
excellent
Range = [0 10]
Four input ar gument s
getfis(a,'input',1,'name')
ans =
service
getfis
344
Five input ar gument s
getfis(a,'input',1,'mf',2)
Name = good
Type = gaussmf
Params =
1.5000 5.0000
Six input ar gument s
getfis(a,'input',1,'mf',2,'name')
ans =
good
See Also setfis, showfis
mam2sug
345
3mam2sug
Purpose Tr ansfor m Mamdani FIS int o a Sugeno FIS.
Synopsis sug_fis=mam2sug(mam_fis)
Description mam2sug(mam_fis) t r ansfor ms a (not necessar ily single out put ) Mamdani FIS
st r uct ur e mam_fis int o a Sugeno FIS st r uct ur e sug_fis. The r et ur ned Sugeno
syst em has const ant out put member ship funct ions. These const ant s ar e
det er mined by t he cent r oids of t he consequent member ship funct ions of t he
or iginal Mamdani syst em. The ant ecedent r emains 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
346
3mf2mf
Purpose Tr anslat es par amet er s bet ween member ship funct ions.
Synopsis outParams = mf2mf(inParams,inType,outType)
Description This funct ion t r anslat es any built in member ship funct ion t ype int o anot her ,
in t er ms of it s par amet er set . In pr inciple, mf2mf mimics t he symmet r y point s
for bot h t he new and old member ship funct ions. Occasionally t his t r anslat ion
r esult s in lost infor mat ion, so t hat if t he out put par amet er s ar e t r anslat ed back
int o t he or iginal member ship funct ion t ype, t he t r ansfor med member ship
funct ion will not look t he same as it did or iginally.
The input ar gument s for mf2mf ar e as follows:
•inParams: t he par amet er s of t he member ship funct ion you ar e t r ansfor ming
•inType: a st r ing name for t he t ype of member ship funct ion you ar e
t r ansfor ming
•outType: a st r ing name for t he new member ship funct ion you ar e
t r ansfor ming t o
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
347
3mfedit
Purpose Member ship funct ion edit or .
Synopsis mfedit('a')
mfedit(a)
mfedit
Description
mfedit('a') gener at es a member ship funct ion edit or t hat allows you t o
inspect and modify all t he member ship funct ions for your FIS st or ed in t he file,
a.fis.
mfedit(a) oper at es on a MATLAB wor kspace var iable, for a FIS st r uct ur e, a.
mfedit alone br ings up t he member ship funct ion edit or wit h no FIS loaded.
For each member ship funct ion you can change t he name, t he t ype, and t he
par amet er s. Eleven built in member ship funct ions ar e pr ovided for you t o
choose fr om, alt hough of cour se you can always cr eat e your own specialized
ver sions. Refer t o “The Member ship Funct ion Edit or ” on page 252 for mor e
infor mat ion about how t o use mfedit.
mfedit
348
Select t he icon for t he var iable on t he upper left side of t he diagr am (under t he
heading “FIS Var iables”) t o display it s associat ed member ship funct ions in t he
plot r egion. Select member ship funct ions by clicking once on t hem or t heir
labels.
Menu Items On t he Member ship Funct ion Edit or , t her e is a menu bar t hat allows you t o
open r elat ed GUI t ools, open and save syst ems, and so on. The Fi le menu for
t he Member ship Funct ion Edit or is t he same as t he one found on t he FIS
Edit or . Refer t o fuzzy on page 329 for mor e infor mat ion.
•Under Edi t , select :
Add MF... t o add member ship funct ions t o t he cur r ent var iable.
Add cus tom MF... t o add a cust omized member ship funct ion t o t he cur r ent
var iable.
Remove current MF t o delet e t he cur r ent member ship funct ion.
Remove all MFs t o delet e all member ship funct ions of t he cur r ent var iable.
Undo t o undo t he most r ecent change.
•Under Vi e w, select :
Edi t FIS properti es ... t o invoke t he FIS Edit or .
Edi t rule s... t o invoke t he Rule Edit or .
Vi ew rule s... t o invoke t he Rule Viewer .
Vi ew s urface ... t o invoke t he Sur face Viewer .
Membership
Function
Popup Menu
Ther e ar e 11 built in member ship funct ions t o choose fr om, and you also have
t he opt ion of inst alling a cust omized member ship funct ion.
See Also fuzzy, ruleedit, ruleview, surfview
newfis
349
3newfis
Purpose Cr eat e new FIS.
Synopsis a=newfis(fisName,fisType,andMethod,orMethod,impMethod, ...
aggMethod,defuzzMethod)
Description This funct ion cr eat es new FIS st r uct ur es. newfis has up t o seven input
ar gument s, and t he out put ar gument is an FIS st r uct ur e. The seven input
ar gument s ar e as follows:
•fisName is t he st r ing name of t he FIS st r uct ur e, fisName.fis you cr eat e.
•fisType is t he t ype of FIS.
•andMethod, orMethod, impMethod, aggMethod, and defuzzMethod,
r espect ively pr ovide t he met hods for AND, OR, implicat ion, aggr egat ion, and
defuzzificat ion.
Examples The following example shows what t he default s ar e for each of t he met hods:
a=newfis('newsys');
getfis(a)
r et ur ns
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
350
3par srule
Purpose Par se fuzzy r ules.
Synopsis fis2 = parsrule(fis,txtRuleList)
fis2 = parsrule(fis,txtRuleList,ruleFormat)
fis2 = parsrule(fis,txtRuleList,ruleFormat,lang)
Description This funct ion par ses t he t ext t hat defines t he r ules (txtRuleList) for a
MATLAB wor kspace FIS var iable, fis, and r et ur ns a FIS st r uct ur e wit h t he
appr opr iat e r ule list in place. If t he or iginal input FIS st r uct ur e, fis, has any
r ules init ially, t hey ar e r eplaced in t he new st r uct ur e, fis2. Thr ee differ ent
r ule for mat s (indicat ed by ruleFormat) ar e suppor t ed: 'verbose', “symbolic,”
and “indexed.” The default for mat is “ver bose”. When t he opt ional language
ar gument , lang, is used, t he r ules ar e par sed in ver bose mode, assuming t he
key wor ds ar e in t he language, lang. This language must be eit her 'english',
'fr ancais', or 'deut sch'. The key language wor ds in English ar e: if, t hen, 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
351
3pimf
Purpose shaped built in member ship funct ion.
Synopsis y = pimf(x,[a b c d])
Description This splinebased cur ve is so named because of it s shape. This member ship
funct ion is evaluat ed at t he point s det er mined by t he vect or x. The par amet er s
a and d locat e t he “feet ” of t he cur ve, while b and c locat e it s “shoulder s.”
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
352
3plot fis
Purpose Plot an FIS.
Synopsis plotfis(fismat)
Description This funct ion displays a high level diagr am of an FIS, fismat. Input s and t heir
member ship funct ions appear t o t he left of t he FIS st r uct ur al char act er ist ics,
while out put s and t heir member ship funct ions appear on t he r ight .
Examples a = readfis('tipper');
plotfis(a)
See Also evalmf, plotmf
plotmf
353
3plot mf
Purpose Plot all of t he member ship funct ions for a given var iable.
Synopsis plotmf(fismat,varType,varIndex)
Description This funct ion plot s all of t he member ship funct ions in t he FIS called fismat
associat ed wit h a given var iable whose t ype and index ar e r espect ively given
by varType ('input' or 'output'), and varIndex. This funct ion can also be
used wit h t he MATLAB funct ion, 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
354
3psigmf
Purpose Built in member ship funct ion composed of t he pr oduct of t wo
sigmoidallyshaped member ship funct ions.
Synopsis y = psigmf(x,[a1 c1 a2 c2])
Description The sigmoid cur ve plot t ed for t he vect or x depends on t wo par amet er s a and c
as given by
psigmf is simply t he pr oduct of t wo such cur ves plot t ed for t he values of t he
vect or x
f
1
(x; a1, c
1
) * f
2
(x; a2, c
2
)
The par amet er s ar e list ed in t he or der : [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
355
3readfis
Purpose Load an FIS fr om t he disk.
Synopsis fismat = readfis('filename')
Description Read a fuzzy infer ence syst em fr om a .fis file (named filename) on t he disk
and br ing t he r esult ing file int o t he wor kspace.
fismat = readfis (no input ar gument s) br ings up a uigetfile dialog box t o
assist wit h t he name and dir ect or y locat ion of t he file.
Examples fismat = readfis('tipper');
getfis(fismat)
r et ur ns
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
356
3rmmf
Purpose To r emove member ship funct ion fr om an FIS.
Synopsis fis = rmmf(fis,'varType',varIndex,'mf',mfIndex)
Description fis = rmmf(fis,varType,varIndex,'mf',mfIndex) r emoves t he member ship
funct ion, mfIndex, of var iable t ype, varType, of index varIndex, fr om t he fuzzy
infer ence syst em associat ed wit h t he wor kspace FIS st r uct ur e, fis:
•The st r ing varType must be 'input' or 'output'.
•varIndex is an int eger for t he index of t he var iable. This index r epr esent s t he
or der in which t he var iables ar e list ed.
•The ar gument 'mf' is a st r ing r epr esent ing t he member ship funct ion.
•mfIndex is an int eger for t he index of t he member ship funct ion. This index
r epr esent s t he or der in which t he member ship funct ions ar e list ed.
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)
r et ur ns
Name = temperature
NumMFs = 1
MFLabels =
cold
Range = [0 100]
b = rmmf(a,'input',1,'mf',1);
getfis(b,'input',1)
r et ur ns
Name = temperature
NumMFs = 0
MFLabels =
Range = [0 100]
See Also addmf, addrule, addvar, plotmf, rmvar
rmvar
357
3rmvar
Purpose To r emove var iables fr om an FIS.
Synopsis [fis2,errorStr] = rmvar(fis,'varType',varIndex)
fis2 = rmvar(fis,'varType',varIndex)
Description fis2 = rmvar(fis,'varType',varIndex) r emoves t he var iable 'varType', of
index varIndex, fr om t he fuzzy infer ence syst em associat ed wit h t he
wor kspace FIS st r uct ur e, fis:
•The st r ing varType must be 'input' or 'output'.
•varIndex is an int eger for t he index of t he var iable. This index r epr esent s t he
or der in which t he var iables ar e list ed.
[fis2,errorStr] = rmvar(fis,'varType',varIndex) r et ur ns any er r or
messages t o t he st r ing, errorStr.
This command aut omat ically alt er s t he r ule list t o keep it s size consist ent wit h
t he cur r ent number of var iables. You must delet e fr om t he FIS any r ule t hat
cont ains a var iable you want t o r emove, befor e r emoving it . You cannot r emove
a fuzzy var iable cur r ent ly in use in t he r ule list .
Examples a = newfis('mysys');
a = addvar(a,'input','temperature',[0 100]);
getfis(a)
rmvar
358
r et ur ns
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)
r et ur ns
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
359
3ruleedit
Purpose Rule edit or and par ser .
Synopsis ruleedit('a')
ruleedit(a)
Description
The Rule Edit or , when invoked using ruleedit('a'), is used t o modify t he
r ules of an FIS st r uct ur e st or ed in a file, a.fis. It can also be used t o inspect
t he r ules being used by a fuzzy infer ence syst em.
To use t his edit or t o cr eat e r ules, you must fir st define all of t he input and
out put var iables you want t o use wit h t he FIS edit or . You can cr eat e t he r ules
using t he list box and check box choices for input and out put var iables,
connect ions, and weight s. Refer t o “The Rule Edit or ” on page 256 for mor e
infor mat ion about how t o use ruleedit.
The synt ax ruleedit(a) is used when you want t o oper at e on a wor kspace
var iable for an FIS st r uct ur e called a.
Language and Format
are options on this
GUI. Languages are
English, Deutsch, and
Francais. Formats are
verbose, symbolic,
and indexed.
ruleedit
360
Menu Items On t he Rule Edit or , t her e is a menu bar t hat allows you t o open r elat ed GUI
t ools, open and save syst ems, and so on. The Fi le menu for t he Rule Edit or is
t he same as t he one found on t he FIS Edit or . Refer t o fuzzy on page 329 for
mor e infor mat ion.
•Use t he following Edi t menu it em:
Undo t o undo t he most r ecent change.
•Use t he following Vi ew menu it ems:
Edi t FIS properti e s... t o invoke t he FIS Edit or .
Edi t membe rshi p functi ons... t o invoke t he Member ship Funct ion
Edit or .
Vi e w rules ... t o invoke t he Rule Viewer .
Vi e w surface... t o invoke t he Sur face Viewer .
•Use t he Opti ons menu it ems:
Language t o select t he language: Engli sh, Deutsch, and Francai s
Format t o select t he for mat :
` verbose uses t he wor ds “if,” “t hen,” “AND,” “OR,” and so on t o cr eat e
act ual sent ences.
` s ymboli c subst it ut es some symbols for t he wor ds used in t he ver bose
mode. For example, “if A AND B t hen C” becomes “A & B => C.”
` i ndexe d mir r or s how t he r ule is st or ed in t he FIS st r uct ur e.
See Also addrule, fuzzy, mfedit, parsrule, ruleview, showrule, surfview
ruleview
361
3ruleview
Purpose Rule viewer and fuzzy infer ence diagr am.
Synopsis ruleview('a')
Description
The Rule Viewer invoked using ruleview('a') depict s t he fuzzy infer ence
diagr am for an FIS st or ed in a file, a.fis. It is used t o view t he ent ir e
implicat ion pr ocess fr om beginning t o end. You can move ar ound t he line
indices t hat cor r espond t o t he input s and t hen wat ch t he syst em r eadjust and
comput e t he new out put . Refer t o “The Rule Viewer ” on page 259 for mor e
infor mat ion about how t o use ruleview.
Menu Items On t he Rule Viewer , t her e is a menu bar t hat allows you t o open r elat ed GUI
t ools, open and save syst ems, and so on. The Fi le menu for t he Rule Viewer is
ruleview
362
t he same as t he one found on t he FIS Edit or . Refer t o fuzzy on page 329 for
mor e infor mat ion.
•Use t he Vi e w menu it ems:
Edi t FIS properti es ... t o invoke t he FIS Edit or
Edi t me mbers hi p functi ons ... t o invoke t he Member ship Funct ion Edit or
Edi t rule s... t o invoke t he Rule Edit or
Vi ew s urface... t o invoke t he Sur face Viewer
•Use t he Opti ons menu it em:
Rule di splay format t o set t he for mat in which t he r ule appear s. If you
click on t he r ule number s on t he left side of t he fuzzy infer ence diagr am,
t he r ule associat ed wit h t hat number will appear in t he St at us Bar at t he
bot t om of t he Rule Viewer .
See Also fuzzy, mfedit, ruleedit, surfview
setfis
363
3set fis
3
Purpose Set fuzzy syst em pr oper t ies.
Synopsis a = setfis(a,'fispropname','newfisprop')
a = setfis(a,'vartype',varindex,'varpropname','newvarprop')
a = setfis(a,'vartype',varindex,'mf',mfindex, ...
'mfpropname','newmfprop');
Description The command setfis can be called wit h t hr ee, five, or seven input ar gument s,
depending on whet her you want t o set a pr oper t y of t he ent ir e FIS st r uct ur e,
for a par t icular var iable belonging t o t hat FIS st r uct ur e, or for a par t icular
member ship funct ion belonging t o one of t hose var iables. The ar gument s ar e:
•a — a var iable name of an FIS fr om t he wor kspace
•'vartype' — a st r ing indicat ing t he var iable t ype: input or output
•varindex — t he index of t he input or out put var iable
•'mf' — a r equir ed st r ing for t he four t h ar gument of a 7ar gument call for
setfis, indicat ing t his var iable is a member ship funct ion
•mfindex — t he index of t he member ship funct ion belonging t o t he chosen
var iable
•'fispropname' — a st r ing indicat ing t he pr oper t y of t he FIS field you want
t o set : name, type, andmethod, ormethod, impmethod, aggmethod,
defuzzmethod
•'newfisprop' — a st r ing descr ibing t he name of t he FIS pr oper t y or met hod
you want t o set
•'varpropname' — a st r ing indicat ing t he name of t he var iable field you want
t o set : name or range
•'newvarprop' — a st r ing descr ibing t he name of t he var iable you want t o set
(for name), or an ar r ay descr ibing t he r ange of t hat var iable (for range)
•'mfpropname'— a st r ing indicat ing t he name of t he member ship funct ion
field you want t o set : name, type, or params.
•'newmfprop' — a st r ing descr ibing t he name or t ype of t he member ship
funct ion field want t o set (for name or type), or an ar r ay descr ibing t he r ange
of t he par amet er s (for params)
setfis
364
Examples Called wit h t hr ee ar gument s,
a = readfis('tipper');
a2 = setfis(a, 'name', 'eating');
getfis(a2, 'name');
Result s in
out =
eating
If used wit h five ar gument s, setfis will updat e t wo var iable pr oper t ies.
a2 = setfis(a,'input',1,'name','help');
getfis(a2,'input',1,'name')
ans =
help
If used wit h seven ar gument s, setfis will updat e any of sever al member ship
funct ion pr oper t ies.
a2 = setfis(a,'input',1,'mf',2,'name','wretched');
getfis(a2,'input',1,'mf',2,'name')
ans =
wretched
See Also getfis
sffis
365
3sffis
Purpose Fuzzy infer ence Sfunct ion for Simulink.
Synopsis output = sffis(t,x,u,flag,fismat)
Description This MEXfile is used by Simulink t o under t ake t he calculat ion nor mally
per for med by evalfis. It has been opt imized t o wor k in t he Simulink
envir onment . This means, among ot her t hings, t hat sffis builds a dat a
st r uct ur e in memor y dur ing t he init ializat ion phase of a Simulink simulat ion,
which it t hen cont inues t o use unt il t he simulat ion is complet e.
The ar gument s t, x, and flag ar e st andar d Simulink Sfunct ion ar gument s
(see Chapt er 8, “SFunct ions” in t he Using S imulink document at ion). The
ar gument u is t he input t o t he MATLAB wor kspace FIS st r uct ur e, fismat. If,
for example, t her e ar e t wo input s t o fismat, t hen u will be a t woelement
vect or .
See Also evalfis, fuzblock
showfis
366
3showfis
Purpose Display annot at ed FIS.
Synopsis showfis(fismat)
Description showfis(fismat) pr int s a ver sion of t he MATLAB wor kspace var iable FIS,
fismat, allowing you t o see t he significance and cont ent s of each field of t he
st r uct ur e.
Examples a = readfis('tipper');
showfis(a)
r et ur ns
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
367
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
368
3showr ule
Purpose Display FIS r ules.
Synopsis showrule(fis)
showrule(fis,indexList)
showrule(fis,indexList,format)
showrule(fis,indexList,format,Lang)
Description This command is used t o display t he r ules associat ed wit h a given syst em. It
can be invoked wit h one t o four ar gument s. The fir st ar gument , fis, is
r equir ed. This is t he MATLAB wor kspace var iable name for a FIS st r uct ur e.
The second (opt ional) ar gument indexList is t he vect or of r ules you want t o
display. The t hir d ar gument (opt ional) is t he st r ing r epr esent ing t he for mat in
which t he r ules ar e r et ur ned. showrule can r et ur n t he r ule in any of t hr ee
differ ent for mat s: 'verbose' (t he default mode, for which English is t he default
language), 'symbolic', and 'indexed', for member ship funct ion index
r efer encing.
When used wit h four ar gument s, t he for t h ar gument must be ver bose, and
showrule(fis,indexList,format,lang) displays t he r ules in t he language
given by lang, which must be eit her 'english', 'francais', or 'deutsch'.
showrule
369
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
370
3sigmf
Purpose Sigmoidallyshaped built in member ship funct ion.
Synopsis y = sigmf(x,[a c])
Description The sigmoidal funct ion, sigmf(x,[a c]), as given below by , is a
mapping on a vect or x, and depends on t wo par amet er s a and c:
Depending on t he sign of t he par amet er a, t he sigmoidal member ship funct ion
is inher ent ly open t o t he r ight or t o t he left , and t hus is appr opr iat e for
r epr esent ing concept s such as “ver y lar ge” or “ver y negat ive.” Mor e
convent ionallooking member ship funct ions can be built by t aking eit her t he
pr oduct or differ ence of t wo differ ent sigmoidal member ship funct ions. You can
find out mor e about t his in t his chapt er ’s ent r ies 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
371
3smf
Purpose S–shaped built in member ship funct ion.
Synopsis y = smf(x,[a b])
Description This splinebased cur ve is a mapping on t he vect or x, and is named because of
it s S–shape. The par amet er s a and b locat e t he ext r emes of t he sloped por t ion
of t he cur ve.
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
372
3subclust
Purpose Find clust er cent er s wit h subt r act ive clust er ing.
Synopsis [C,S] = subclust(X,radii,xBounds,options)
Description This funct ion est imat es t he clust er cent er s in a set of dat a by using t he
subt r act ive clust er ing met hod. The subt r act ive clust er ing met hod assumes
each dat a point is a pot ent ial clust er cent er and calculat es a measur e of t he
likelihood t hat each dat a point would define t he clust er cent er , based on t he
densit y of sur r ounding dat a point s. The algor it hm
•Select s t he dat a point wit h t he highest pot ent ial t o be t he fir st clust er cent er
•Removes all dat a point s in t he vicinit y of t he fir st clust er cent er (as
det er mined by radii), in or der t o det er mine t he next dat a clust er and it s
cent er locat ion
•It er at es on t his pr ocess unt il all of t he dat a is wit hin radii of a clust er cent er
The subt r act ive clust er ing met hod is an ext ension of t he mount ain clust er ing
met hod pr oposed by R. Yager .
The mat r ix X cont ains t he dat a t o be clust er ed; each r ow of X is a dat a point .
The var iable radii is a vect or of ent r ies bet ween 0 and 1 t hat specifies a clust er
cent er ’s r ange of influence in each of t he dat a dimensions, assuming t he dat a
falls wit hin a unit hyper box. Small radii values gener ally r esult in finding a
few lar ge clust er s. Good values for radii ar e usually bet ween 0.2 and 0.5.
For example, if t he dat a dimension is t wo (X has t wo columns),
radii = [0.5 0.25] specifies t hat t he r ange of influence in t he fir st dat a
dimension is half t he widt h of t he dat a space and t he r ange of influence in t he
second dat a dimension is one quar t er t he widt h of t he dat a space. If radii is a
scalar , t hen t he scalar value is applied t o all dat a dimensions, i.e., each clust er
cent er will have a spher ical neighbor hood of influence wit h t he given r adius.
xBounds is a 2byN mat r ix t hat specifies how t o map t he dat a in X int o a unit
hyper box, wher e N is t he dat a dimension. This ar gument is opt ional if X is
alr eady nor malized. The fir st r ow cont ains t he minimum axis r ange values and
t he second r ow cont ains t he maximum axis r ange values for scaling t he dat a in
each dimension. For example, xBounds = [10 5; 10 5] specifies t hat dat a values
in t he fir st dat a dimension ar e t o be scaled fr om t he r ange [10 +10] int o values
in t he r ange [0 1]; dat a values in t he second dat a dimension ar e t o be scaled
fr om t he r ange [5 +5] int o values in t he r ange [0 1]. If xBounds is an empt y
subclust
373
mat r ix or not pr ovided, t hen xBounds default s t o t he minimum and maximum
dat a values found in each dat a dimension.
The options vect or can be used for specifying clust er ing algor it hm par amet er s
t o over r ide t he default values. These component s of t he vect or options ar e
specified as follows:
•options(1) = quashFactor: This is t he fact or used t o mult iply t he r adii
values t hat det er mine t he neighbor hood of a clust er cent er , so as t o quash
t he pot ent ial for out lying point s t o be consider ed as par t of t hat clust er .
(default : 1.25)
•options(2) = acceptRatio: This set s t he pot ent ial, as a fr act ion of t he
pot ent ial of t he fir st clust er cent er , above which anot her dat a point will be
accept ed as a clust er cent er . (default : 0.5)
•options(3) = rejectRatio: This set s t he pot ent ial, as a fr act ion of t he
pot ent ial of t he fir st clust er cent er , below which a dat a point will be r eject ed
as a clust er cent er . (default : 0.15)
•options(4) = verbose: If t his t er m is not zer o, t hen pr ogr ess infor mat ion
will be pr int ed as t he clust er ing pr ocess pr oceeds. (default : 0)
The funct ion r et ur ns t he clust er cent er s in t he mat r ix C; each r ow of C cont ains
t he posit ion of a clust er cent er . The r et ur ned S vect or cont ains t he sigma values
t hat specify t he r ange of influence of a clust er cent er in each of t he dat a
dimensions. All clust er cent er s shar e t he same set of sigma values.
Examples [C,S] = subclust(X,0.5)
This is t he minimum number of ar gument s needed t o use t his funct ion. Ar ange
of influence of 0.5 has been specified for all dat a dimensions.
[C,S] = subclust(X,[0.5 0.25 0.3],[],[2.0 0.8 0.7])
This assumes t he dat a dimension is 3 (X has 3 columns) and uses a r ange of
influence of 0.5, 0.25, and 0.3 for t he fir st , second and t hir d dat a dimension,
r espect ively. The scaling fact or s for mapping t he dat a int o a unit hyper box will
be obt ained fr om t he minimum and maximum dat a values. The squashFactor
is set t o 2.0, indicat ing t hat we only want t o find clust er s t hat ar e far fr om each
ot her . The acceptRatio is set t o 0.8, indicat ing t hat we will only accept dat a
point s t hat have a ver y st r ong pot ent ial for being clust er cent er s. The
subclust
374
rejectRatio is set t o 0.7, indicat ing t hat we want t o r eject all dat a point s
wit hout a st r ong pot ent ial.
See Also genfis2
References Chiu, S., “Fuzzy Model Ident ificat ion Based on Clust er Est imat ion,” J ournal of
Intelligent & Fuzzy S ystems, Vol. 2, No. 3, Sept . 1994.
Yager , R. and D. Filev, “Gener at ion of Fuzzy Rules by Mount ain Clust er ing,”
J ournal of Intelligent & Fuzzy S ystems, Vol. 2, No. 3, pp. 209219, 1994.
surfview
375
3sur fview
Purpose Out put sur face viewer .
Synopsis surfview('a')
Description
The Sur face Viewer invoked using surfview('a') is a GUI t ool t hat let s you
examine t he out put sur face of an FIS st or ed in a file, a.fis, for any one or t wo
input s. Since it does not alt er t he fuzzy syst em or it s associat ed FIS st r uct ur e
in any way, it is a r eadonly edit or . Using t he popup menus, you select t he t wo
input var iables you want assigned t o t he t wo input axes (X and Y), as well t he
out put var iable you want assigned t o t he out put (or Z) axis. Select t he
Evaluate but t on t o per for m t he calculat ion and plot t he out put sur face.
By clicking on t he plot axes and dr agging t he mouse, you can manipulat e t he
sur face so t hat you can view it fr om differ ent angles.
If t her e ar e mor e t han t wo input s t o your syst em, you must supply t he const ant
values associat ed wit h any unspecified input s in t he r efer ence input sect ion.
Refer t o “The Sur face Viewer ” on page 261 for mor e infor mat ion about how t o
use surfview.
surfview
376
Menu Items On t he Sur face Viewer , t her e is a menu bar t hat allows you t o open r elat ed GUI
t ools, open and save syst ems, and so on. The Fi le menu for t he Sur face Viewer
is t he same as t he one found on t he FIS Edit or . Refer t o fuzzy on page 329 for
mor e infor mat ion.
•Use t he Vi e w menu it ems:
Edi t FIS properti es ... t o invoke t he FIS Edit or .
Edi t me mbers hi p functi ons ... t o invoke t he Member ship Funct ion Edit or .
Edi t rule s... t o invoke t he Rule Edit or .
Vi ew rule s... t o invoke t he Rule Viewer .
•Use t he Opti ons menu it ems:
Plot t o choose among eight differ ent kinds of plot st yles.
Color Map t o choose among sever al differ ent color schemes.
Always evaluate t o aut omat ically evaluat e and plot a new sur face ever y
t ime you make a change t hat affect s t he plot (like changing t he number of
gr id point s). This is t he default opt ion. To deselect t his opt ion, select it once
mor e.
See Also anfisedit, fuzzy, gensurf, mfedit, ruleedit, ruleview
trapmf
377
3t r apmf
Purpose Tr apezoidalshaped built in member ship funct ion.
Synopsis y = trapmf(x,[a b c d])
Description The t r apezoidal cur ve is a funct ion of a vect or , x, and depends on four scalar
par amet er s a, b, c, and d, as given by
or , mor e compact ly, by
The par amet er s a and d locat e t he “feet ” of t he t r apezoid and t he par amet er s b
and c locat e t he “shoulder s.”
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
378
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf,
trimf, zmf
trimf
379
3t r imf
Purpose Tr iangular shaped built in member ship funct ion.
Synopsis y = trimf(x,params)
y = trimf(x,[a b c])
Description The t r iangular cur ve is a funct ion of a vect or , x, and depends on t hr ee scalar
par amet er s a, b, and c, as given by
or , mor e compact ly, by
The par amet er s a and c locat e t he “feet ” of t he t r iangle and t he par amet er c
locat es t he peak.
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
380
See Also dsigmf, gaussmf, gauss2mf, gbellmf, evalmf, mf2mf, pimf, psigmf, sigmf, smf,
trapmf
writefis
381
3wr it efis
Purpose Save an FIS t o t he disk.
Synopsis writefis(fismat)
writefis(fismat,'filename')
writefis(fismat,'filename','dialog'
Description writefis saves a MATLAB wor kspace FIS st r uct ur e, fismat, as a .fis file on
disk.
writefis(fismat) br ings up a dialog box t o assist wit h t he naming and
dir ect or y locat ion of t he file.
writefis(fismat,'filename') wr it es a .fis file cor r esponding t o t he FIS
st r uct ur e, fismat, t o a disk file called filename.fis. No dialog box is used and
t he file is saved t o t he cur r ent dir ect or y.
writefis(fismat,'filename','dialog') br ings up a dialog box wit h t he
default name filename.fis supplied.
The ext ension .fis is only added t o filename if it is not alr eady included in t he
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
382
3zmf
Purpose Zshaped built in member ship funct ion.
Synopsis y = zmf(x,[a b])
Description This splinebased funct ion of x is so named because of it s Zshape. The
par amet er s a and b locat e t he ext r emes of t he sloped por t ion of t he cur ve.
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]
I1
Index
A
addmf 72, 76, 36
addrule 72, 76, 38
addvar 76, 39
aggr egat ion 36, 40, 44, 60, 63, 86, 132, 133
AND 30, 37, 63, 103
ANFIS 93
anfis 7, 92, 95, 104, 109, 112, 114, 125, 310
opt ions 116
ANFIS Edit or GUI 7, 45, 92, 95, 106, 109, 114,
314
anfisedit 67, 93, 95, 314
ant ecedent 35, 37, 59, 74, 86, 88, 132
B
backpr opagat ion 104
C
chaot ic t ime ser ies 120
checking dat a 94, 118
checking er r or 119
clust er ing 120, 121, 128, 132
clust er ing algor it hms 133
clust er ing GUI 128
consequent 32, 35, 40, 59, 74, 86, 132
ant ecedent 37
convertfis 316
D
defuzz 317
defuzzificat ion 32, 36, 40, 49, 63, 95, 132
defuzzify 32, 41
degr ee of member ship 20, 24, 33, 35, 38
distfcm 121
dsigmf 27, 318
E
er r or t oler ance 104
evalfis 73, 126, 319, 326
evalmf 321
F
fcm (fuzzy cmeans) 120, 128, 322
findcluster 128, 324
FIS 43, 47, 49, 53, 58, 65, 67, 73, 84, 92, 95, 109,
125, 132, 310
Ccode 130
Edit or 45, 49, 68, 115
files 76
gener at ing 100
Mamdanit ype 49, 86, 91
mat r ix 73
saving a FIS 62
st r uct ur e 93, 115, 117
Sugenot ype 86, 88, 95
Sugenot ype S ee also Sugenot ype infer ence
97
fuzblock 83, 327
fuzdemos 328
fuzzificat ion 32, 37, 42, 49, 132
fuzzy 329
fuzzy clust er ing 115, 120
fuzzy cmeans clust er ing 322
Fuzzy Infer ence Syst em (FIS) 19, 45, 132
fuzzy oper at or s 29, 32, 37, 39, 44, 58, 63, 71, 131
fuzzy set 20, 23, 26, 35, 38, 40, 60, 86, 88, 132
Index
I2
G
gauss2mf 27, 332
gaussian 27
gaussmf 27, 334
gbellmf 27, 335
genfis 111
genfis1 101, 336
genfis2 101, 126, 338
gensurf 70, 88, 90, 340
getfis 66, 76, 89, 342
glossar y 132
gr id par t it ion 100
H
hybr id met hod 104
I
ift hen r ules 32
ant ecedent 32
consequent 32
implicat ion 32, 35, 37, 39, 43, 60, 63, 86
implicat ion S ee also ift hen r ules 32, 133
initfcm 121
L
logical oper at ions 28
M
mam2sug 345
Mamdani’s met hod 36
Mamdanist yle infer ence 133
Mamdanit ype infer ence 35, 49, 86, 90
max 41, 43
member ship funct ion 23, 28, 35, 53, 55, 118, 133
mf edit or 103
Member ship Funct ion Edit or 45, 47, 52
member ship funct ions
bell 27
cust om 63
Gaussian 27
Pi 27
S 27
sigmoidal 27
Z 27
MF S ee also member ship funct ion
mf2mf 346
mfedit 347
min 43
model validat ion 94, 98
N
neur ofuzzy infer ence 93
newfis 72, 349
NOT 30, 103
O
OR 30, 37, 43, 103
P
parsrule 350
pimf 28, 351
plotfis 68, 352
plotmf 68, 90, 353
pr obabilist ic OR 39
pr obor 41
psigmf 27, 354
Index
I3
R
readfis 65, 73, 88, 355
rmmf 76, 356
rmvar 76, 357
Rule Edit or 45, 56
r ule for mat s 315, 360
Rule Viewer 45, 47, 59
ruleedit 359
ruleview 361
S
setfis 66, 76, 363
sffis 84, 365
showfis 67, 74, 76, 366
showrule 368
sigmf 27, 370
Simulink blocks
fuzzy cont r oller wit h r uleviewer 81
Fuzzy Logic Cont r oller 79, 83
Simulink, wor king wit h 78
singlet on 36
sltank 79
smf 28, 371
st andalone Ccode 130
st andalone fuzzy infer ence engine 130
st ep size 117
structure.field synt ax 66, 73
subclust 372
subt r act ive clust er ing 100, 123, 128
Sugeno 123
Sugenot ype FIS S ee also Sugenot ype infer ence
101
Sugenot ype infer ence 37, 45, 50, 86, 88, 120, 124,
133
sum 41
Sur face Viewer 45, 47, 61
surfview 375
T
Tconor m 31, 133
t est ing dat a 94, 97
Tnor m 31, 133
t r aining dat a 95, 99, 115
t r aining er r or 117
t r apezoidal 26
trapmf 26, 377
trimf 379
W
writefis 381
Z
zmf 28, 382
How to Contact The MathWorks:
PHONE
¤
FAX MAIL
5086477000 5086477001
Phone Fax Mail
u
INTERNET
The MathWorks, Inc. 24 Prime Park Way Natick, MA 017601500
http://www.mathworks.com ftp.mathworks.com comp.softsys.matlab
Web Anonymous FTP server Newsgroup Technical support Product enhancement suggestions Bug reports Documentation error reports Subscribing user registration Order status, license renewals, passcodes Sales, pricing, and general information
@
support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com subscribe@mathworks.com service@mathworks.com info@mathworks.com
Fuzzy Logic Toolbox User’s Guide © COPYRIGHT 1995  1999 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. U.S. GOVERNMENT: If Licensee is acquiring the Programs on behalf of any unit or agency of the U.S. Government, the following shall apply: (a) For units of the Department of Defense: the Government shall have only the rights specified in the license under which the commercial computer software or commercial software documentation was obtained, as set forth in subparagraph (a) of the Rights in Commercial Computer Software or Commercial Software Documentation Clause at DFARS 227.72023, therefore the rights set forth herein shall apply; and (b) For any other unit or agency: NOTICE: Notwithstanding any other lease or license agreement that may pertain to, or accompany the delivery of, the computer software and accompanying documentation, the rights of the Government regarding its use, reproduction, and disclosure are as set forth in Clause 52.22719 (c)(2) of the FAR. MATLAB, Simulink, Stateflow, Handle Graphics, and RealTime Workshop are registered trademarks and Target Language Compiler are trademarks of The MathWorks, Inc. Other product or brand names are trademarks or registered trademarks of their respective holders.
Printing History: January 1995 April 1997 January 1998 January 1999
First printing Second printing Third printingRevised for MATLAB 5.2 Minor revisions for Release 11 (Online only)
Forward
The past few years have witnessed a rapid growth in the number and variety of applications of fuzzy logic. The applications range from consumer products such as cameras, camcorders, washing machines, and microwave ovens to industrial process control, medical instrumentation, decisionsupport systems, and portfolio selection. To understand the reasons for the growing use of fuzzy logic it is necessary, first, to clarify what is meant by fuzzy logic. Fuzzy logic has two different meanings. In a narrow sense, fuzzy logic is a logical system, which is an extension of multivalued logic. But in a wider sense—which is in predominant use today—fuzzy logic (FL) is almost synonymous with the theory of fuzzy sets, a theory which relates to classes of objects with unsharp boundaries in which membership is a matter of degree. In this perspective, fuzzy logic in its narrow sense is a branch of FL. What is important to recognize is that, even in its narrow sense, the agenda of fuzzy logic is very different both in spirit and substance from the agendas of traditional multivalued logical systems. In the Fuzzy Logic Toolbox, fuzzy logic should be interpreted as FL, that is, fuzzy logic in its wide sense. The basic ideas underlying FL are explained very clearly and insightfully in the Introduction. What might be added is that the basic concept underlying FL is that of a linguistic variable, that is, a variable whose values are words rather than numbers. In effect, much of FL may be viewed as a methodology for computing with words rather than numbers. Although words are inherently less precise than numbers, their use is closer to human intuition. Furthermore, computing with words exploits the tolerance for imprecision and thereby lowers the cost of solution. Another basic concept in FL, which plays a central role in most of its applications, is that of a fuzzy ifthen rule or, simply, fuzzy rule. Although rulebased systems have a long history of use in AI, what is missing in such systems is a machinery for dealing with fuzzy consequents and/or fuzzy antecedents. In fuzzy logic, this machinery is provided by what is called the calculus of fuzzy rules. The calculus of fuzzy rules serves as a basis for what might be called the Fuzzy Dependency and Command Language (FDCL). Although FDCL is not used explicitly in Fuzzy Logic Toolbox, it is effectively one of its principal constituents. In this connection, what is important to
Forward
recognize is that in most of the applications of fuzzy logic, a fuzzy logic solution is in reality a translation of a human solution into FDCL. What makes the Fuzzy Logic Toolbox so powerful is the fact that most of human reasoning and concept formation is linked to the use of fuzzy rules. By providing a systematic framework for computing with fuzzy rules, the Fuzzy Logic Toolbox greatly amplifies the power of human reasoning. Further amplification results from the use of MATLAB and graphical user interfaces – areas in which The MathWorks has unparalleled expertise. A trend which is growing in visibility relates to the use of fuzzy logic in combination with neurocomputing and genetic algorithms. More generally, fuzzy logic, neurocomputing, and genetic algorithms may be viewed as the principal constituents of what might be called soft computing. Unlike the traditional, hard computing, soft computing is aimed at an accommodation with the pervasive imprecision of the real world. The guiding principle of soft computing is: Exploit the tolerance for imprecision, uncertainty, and partial truth to achieve tractability, robustness, and low solution cost. In coming years, soft computing is likely to play an increasingly important role in the conception and design of systems whose MIQ (Machine IQ) is much higher than that of systems designed by conventional methods. Among various combinations of methodologies in soft computing, the one which has highest visibility at this juncture is that of fuzzy logic and neurocomputing, leading to socalled neurofuzzy systems. Within fuzzy logic, such systems play a particularly important role in the induction of rules from observations. An effective method developed by Dr. Roger Jang for this purpose is called ANFIS (Adaptive NeuroFuzzy Inference System). This method is an important component of the Fuzzy Logic Toolbox. The Fuzzy Logic Toolbox is highly impressive in all respects. It makes fuzzy logic an effective tool for the conception and design of intelligent systems. The Fuzzy Logic Toolbox is easy to master and convenient to use. And last, but not least important, it provides a readerfriendly and uptodate introduction to the methodology of fuzzy logic and its wideranging applications.
Lotfi A. Zadeh Berkeley, CA January 10, 1995
. . . . . . . . . . . . NonFuzzy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Membership Functions . . . . . . . 7 Installation . . . . . . . Why Use Fuzzy Logic? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 Some Observations . . . . . . . . 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Tutorial 2 The Big Picture . . . . . . . . . . . . . . . . . . . . . . 7 Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . When Not to Use Fuzzy Logic . . . . . . . . . . . . . 18 The NonFuzzy Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Introduction 1 What Is Fuzzy Logic? . . . . . . . . . 18 Foundations of Fuzzy Logic . . . . . . . . . . . . . 19 The Fuzzy Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 20 24 28 i . . . . . . . . . . What Can the Fuzzy Logic Toolbox Do? . . . . . . . . . . . . . . . . . . . . . . . . . . Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Contents Before You Begin What Is the Fuzzy Logic Toolbox? . . . . . . . . . . . . . . . . . . . . . Fuzzy Sets . . . . . . . . . . . 12 15 16 16 An Introductory Example: Fuzzy vs. . . . . . . . . . . . . . . . . . . . 6 How to Use This Guide .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Customizing Your Fuzzy System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 SugenoType Fuzzy Inference . . The FIS Editor . . . . . . . from the Top . . . . . . . . . . . Customization . . 89 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Surface Viewer . . . . . . . . . . . . . . . . . . . . . . . . 36 37 42 43 45 45 48 49 52 56 59 61 62 63 65 67 70 73 73 Working with Simulink . . . . . . . . . . . . . . . . . . . . . . . . . The Rule Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . System Display Functions . . . . The Membership Function Editor . . . . . . . . . . . . . . Getting Started . . . . . . . . 86 An Example: Two Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Fuzzy Inference Diagram . . . . . . . . . . . Some Constraints of anfis . . . . . . . . . . . . . . . . . . . . . . . Building a System from Scratch . . . . . . . . . . . . . . . . . . . . . 32 Fuzzy Inference Systems . . . . . . . . . . . . . . Dinner for Two. . . ANFIS Editor GUI Example 1: 92 92 93 94 95 95 ii Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 An Example: Water Level Control . . . . . . . . . . . . . . . . . . . . . . . . . . .IfThen Rules . . . . . . . . . . . . . . . . . . . . . . . . . . Dinner for Two. . . . . . . . . . . . . The Rule Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Importing and Exporting from the GUI Tools . . . . . . . . The FIS Structure . . . . . . Familiarity Breeds Validation: Know Your Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 anfis and the ANFIS Editor GUI . . . . . . . Building Systems with the Fuzzy Logic Toolbox . . 78 Building Your Own Fuzzy Simulink Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A Modeling Scenario . . . . . . . . . . . . . . . . . . . . . . . The ANFIS Editor GUI . . . . . . Reprise . . . . . . . . . . . . Working from the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Model Learning and Inference Through ANFIS . . . . . FIS Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 References . . . . . . . . . . . . . . . . . Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 Fuzzy CMeans Clustering . . . . . . . . . . . . . . . . . 32 32 33 34 34 35 iii . 120 Subtractive Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 anfis from the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . FIS Data Structure Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Reference 3 GUI Tools . . . . . . . Membership Functions . Simulink Blocks . . . . . . . . . . . . . . 123 StandAlone CCode Fuzzy Inference Engine . . . . . . . . . . . . . . . . . . . . . .Checking Data Helps Model Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 ANFIS Editor GUI Example 2: Checking Data Doesn’t Validate Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 More on anfis and the ANFIS Editor GUI . . . . . . . . . . . . . . . . . . . Advanced Techniques . . . . 114 Fuzzy Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
iv Contents .
. . . . . . . . . . . . . . Typographical Conventions . . . . . . . . . . . . . . . 2 3 3 4 . Installation . . . .Before You Begin What Is the Fuzzy Logic Toolbox? How to Use This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
although you can work entirely from the command line if you prefer. The toolbox provides three categories of tools: • Command line functions • Graphical. the toolbox provides a number of interactive tools that let you access many of the functions through a GUI. series of MATLAB statements that implement specialized fuzzy logic algorithms. 6 . The third category of tools is a set of blocks for use with the Simulink simulation software. What Is the Fuzzy Logic Toolbox? The Fuzzy Logic Toolbox is a collection of functions built on the MATLAB ® numeric computing environment. Together. or you can even build standalone C 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. It provides tools for you to create and edit fuzzy inference systems within the framework of MATLAB. analysis. You can view the MATLAB code for these functions using the statement type function_name You can change the way any toolbox function works by copying and renaming the Mfile. Secondly. or if you prefer you can integrate your fuzzy systems into simulations with Simulink®. Many of these functions are MATLAB Mfiles. It explains how to use this guide and points you to additional books for toolbox installation information.based tools provide an environment for fuzzy inference system design.Before You Begin This section describes how to use the Fuzzy Logic Toolbox. and implementation. then modifying your copy. the GUI. These are specifically designed for high speed fuzzy logic inference in the Simulink environment. You can also extend the toolbox by adding your own Mfiles. interactive tools • Simulink blocks and examples The first category of tools is made up of functions that you can call from the command line or from your own applications.
“Reference. the descriptions include options for invoking the tool. see the Installation Guide for UNIX. begin with Chapter 1. check for a subdirectory named fuzzy within the main toolbox directory or folder. you can open an example system right away by typing fuzzy tipper This brings up the Fuzzy Inference System (FIS) editor for an example decision making problem that has to do with how to tip in a restaurant. Reference descriptions include a synopsis of the function’s syntax. The basic functionality of this tool can be found in the section in Chapter 2 entitled. Installation To install this toolbox on a workstation or a large machine. a description of the function’s algorithm. “Introduction. “Building Systems with the Fuzzy Logic Toolbox. Many reference descriptions also include helpful examples.” This chapter introduces the motivation behind fuzzy logic and leads you smoothly into the tutorial. 7 . If you are an experienced fuzzy logic user. If you just want an overview of each graphical tool and examples of specific fuzzy system tasks.” for information on specific tools or functions. turn directly to the section in Chapter 2 entitled. you may want to start at the beginning of Chapter 2.How to Use This Guide If you are new to fuzzy logic. To determine if the Fuzzy Logic Toolbox is already installed on your system.” If you just want to start as soon as possible and experiment. “anfis and the ANFIS Editor GUI. To install the toolbox on a PC or Macintosh. and references to additional reading material. see the Installation Guide for PC and Macintosh. as well as a complete explanation of options and operation.” to make sure you are comfortable with the fuzzy logic terminology in the Fuzzy Logic Toolbox.” This section does not include information on the adaptive data modeling application covered by the toolbox function anfis. “Tutorial. All toolbox users should use Chapter 3. For GUIbased tools.
) Mathematical expressions Variables in italics. (Use EquationVariables tag.) Example Example code To assign the value 5 to A. The magic function uses the syntax M = magic(n) Monospace type for text that must appear as shown.) Monospace type (Use Code tag. and constants in standard type. (Use Codeital tag. operators.) This vector represents the polynomial p = x2 + 2x + 3 MATLAB output MATLAB responds with A= 5 8 . enter A = 5 Function names Function syntax Monospace type (Use Code tag. Functions.) Monospace italics for components you can replace with any variable.) The cos function finds the cosine of each array element. capital letter (Use MenuBodytext tag. (Use Code tag.) Keys Boldface with an initial Press the Return key.Before You Begin Typographical Conventions To Indicate This Guide Uses Monospace type (Use Code tag.
menu items. capital letter (Use MenuBodytext tag. and controls New terms Boldface with an initial Choose the File menu. 9 .) NCS italics (Use Body textital tag.To Indicate This Guide Uses Example Menu names.) An array is an ordered collection of information.
Before You Begin 10 .
. . . . . Some Observations . . . . . . . . . . . . . .1 Introduction What Is Fuzzy Logic? . . . . . . . . . . What Can the Fuzzy Logic Toolbox Do? . . . . . . . . . . . 12 15 16 16 18 19 113 114 An Introductory Example: Fuzzy vs. . . . . . . . . . . . . . . . . . . . . . . . . . . . NonFuzzy The NonFuzzy Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Fuzzy Approach . Why Use Fuzzy Logic? . . When Not to Use Fuzzy Logic . . . . .
precise statements lose meaning and meaningful statements lose precision. In this sense fuzzy logic is both old and new because. Fuzzy logic is a fascinating area of research because it does a good job of trading off between significance and precision—something that humans have been managing for a very long time. but once you become acquainted with it. Don’t be penny wise and pound foolish. —Albert Einstein As complexity rises. they do not refer to reality. —Henri Matisse Sometimes the more measurable drives out the most important. Fuzzy logic sometimes appears exotic or intimidating to those unfamiliar with it. and this is no exception. And so far as they are certain. —H. it seems almost surprising that no one attempted it sooner. they are not certain. —Lotfi Zadeh Some pearls of folk wisdom also echo these thoughts: Don’t lose sight of the forest for the trees. L. —René Dubos Vagueness is no more to be done away with in the world of logic than friction in mechanics. Mencken So far as the laws of mathematics refer to reality. Here is what some clever people have said in the past: Precision is not truth. —Charles Sanders Peirce I believe that nothing is unconditionally true. The Fuzzy Logic Toolbox for use with MATLAB is a tool for solving problems with fuzzy logic. and hence I am opposed to every statement of positive truth and every man who makes it. 12 .1 Introduction What Is Fuzzy Logic? Fuzzy logic is all about the relative importance of precision: How important is it to be exactly right when a rough answer will do? All books on fuzzy logic begin with a few good quotes on this very topic.
the concepts of fuzzy logic reach right down to our bones.What Is Fuzzy Logic? although the modern and methodical science of fuzzy logic is still young. and I’ll shift the gears for you.3 m/sec. LOOK OUT!! Precision Significance Fuzzy logic is a convenient way to map an input space to an output space. You tell me how hot you want the water. 13 . Precision and Significance in the Real World A 1500 kg mass is approaching your head at 45. and I’ll adjust the faucet valve to the right setting. This is the starting point for everything else.” What do I mean by mapping input space to output space? Here are a few examples: You tell me how good your service was at a restaurant. and I’ll focus the lens for you. and the great emphasis here is on the word “convenient. You tell me how fast the car is going and how hard the motor is working. You tell me how far away the subject of your photograph is. and I’ll tell you what the tip should be.
Input Space (all possible service quality ratings) Output Space (all possible tips) tonight's service quality Black Box the “right” tip for tonight An inputoutput map for the tipping problem: “Given the quality of service. who is considered to be the father of fuzzy logic.1 Introduction A graphical example of an inputoutput map is shown below. how much should I tip?” It’s all just a matter of mapping inputs to the appropriate outputs. just to name a few of the possible options. it turns out that fuzzy is often the very best way. What could go in the black box? Any number of things: fuzzy systems. Of the dozens of ways to make the black box work. once remarked: “In almost every case you can build the same product without fuzzy logic. Why should that be? As Lotfi Zadeh. linear systems. expert systems. differential equations. Clearly the list could go on and on. but fuzzy is faster and cheaper.” 14 . interpolated multidimensional lookup tables. or even a spiritual advisor. Between the input and the output we’ll put a black box that does the work. neural networks.
Fuzzy systems don’t necessarily replace conventional control methods. With any given system. most things are imprecise even on careful inspection. has been shaped by thousands of years of human history to be convenient and efficient. something we use every day. What makes fuzzy nice is the “naturalness” of its approach and not its farreaching complexity. In direct contrast to neural networks. Since fuzzy logic is built 15 . fuzzy logic lets you rely on the experience of people who already understand your system. In many cases fuzzy systems augment them and simplify their implementation. • Fuzzy logic is conceptually easy to understand. Fuzzy reasoning builds this understanding into the process rather than tacking it onto the end. • Fuzzy logic is tolerant of imprecise data. The basis for fuzzy logic is the basis for human communication. This observation underpins many of the other statements about fuzzy logic. • Fuzzy logic is based on natural language. • Fuzzy logic is flexible. Natural language. impenetrable models. but more than that. We are generally unaware of this because ordinary language is. You can create a fuzzy system to match any set of inputoutput data. Sentences written in ordinary language represent a triumph of efficient communication. which take training data and generate opaque. it’s easy to massage it or layer more functionality on top of it without starting again from scratch.What Is Fuzzy Logic? Why Use Fuzzy Logic? Here is a list of general observations about fuzzy logic. • Fuzzy logic can be blended with conventional control techniques. This process is made particularly easy by adaptive techniques like ANFIS (Adaptive NeuroFuzzy Inference Systems). which are available in the Fuzzy Logic Toolbox. The last statement is perhaps the most important one and deserves more discussion. The mathematical concepts behind fuzzy reasoning are very simple. Everything is imprecise if you look closely enough. of course. that which is used by ordinary people on a daily basis. • Fuzzy logic can model nonlinear functions of arbitrary complexity. • Fuzzy logic can be built on top of the experience of experts.
use it. If you have access to Simulink. fuzzy logic is easy to use. You can create these systems using graphical tools or commandline functions. you’ll see it can be a very powerful tool for dealing quickly and efficiently with imprecision and nonlinearity. What Can the Fuzzy Logic Toolbox Do? The Fuzzy Logic Toolbox allows you to do several things. without the need for Simulink. If you find it’s not convenient. Fuzzy logic is the codification of common sense—use common sense when you implement it and you will probably make the right decision. or you can generate them automatically using either clustering or adaptive neurofuzzy techniques. try something else. if you take the time to become familiar with fuzzy logic. When Not to Use Fuzzy Logic Fuzzy logic is not a cureall. This is made possible by a standalone Fuzzy Inference Engine that reads the fuzzy systems saved from a MATLAB session. for example. The toolbox also lets you run your own standalone C programs directly. Many controllers. When should you not use fuzzy logic? The safest statement is the first one made in this introduction: fuzzy logic is a convenient way to map an input space to an output space.1 Introduction atop the structures of qualitative description used in everyday language. do a fine job without using fuzzy logic. However. 16 . If a simpler solution already exists. but the most important thing it lets you do is create and edit fuzzy inference systems. you can easily test your fuzzy system in a block diagram simulation environment.
Neural Network. Fuzzy Inference System Fuzzy Logic Toolbox Simulink Standalone Fuzzy Engine Userwritten Mfiles Other toolboxes MATLAB Because of the integrated nature of MATLAB’s environment.What Is Fuzzy Logic? You can customize the standalone engine to build fuzzy inference into your own code. you can create your own tools to customize the Fuzzy Logic Toolbox or harness it with another toolbox. All provided code is ANSI compliant. 17 . such as the Control System. or Optimization Toolbox. to mention only a few of the possibilities.
1
Introduction
An Introductory Example: Fuzzy vs. NonFuzzy
A specific example would be helpful at this point. To illustrate the value of fuzzy logic, we’ll show two different approaches to the same problem: linear and fuzzy. First we will work through this problem the conventional (nonfuzzy) way, writing MATLAB commands that spell out linear and piecewiselinear relations. Then we’ll take a quick look at the same system using fuzzy logic. Consider the tipping problem: what is the “right” amount to tip your waitperson? Here is a clear statement of the problem.
The Basic Tipping Problem. Given a number between 0 and 10 that represents the quality of service at a restaurant (where 10 is excellent), what should the tip be?
Cultural footnote: This problem is based on tipping as it is typically practiced in the United States. An average tip for a meal in the U.S. is 15%, though the actual amount may vary depending on the quality of the service provided.
18
An Introductory Example: Fuzzy vs. NonFuzzy
The NonFuzzy Approach
Let’s start with the simplest possible relationship. Suppose that the tip always equals 15% of the total bill.
tip = 0.15
0.25
0.2
0.15
tip
0.1
0.05
0 0
2
4 service
6
8
10
This doesn’t really take into account the quality of the service, so we need to add a new term to the equation. Since service is rated on a scale of 0 to 10, we might have the tip go linearly from 5% if the service is bad to 25% if the service is excellent. Now our relation looks like this:
tip=0.20/10*service+0.05
0.25
0.2
tip
0.15
0.1
0.05 0
2
4 service
6
8
10
19
1
Introduction
So far so good. The formula does what we want it to do, and it’s pretty straightforward. However, we may want the tip to reflect the quality of the food as well. This extension of the problem is defined as follows:
The Extended Tipping Problem. Given two sets of numbers between 0 and 10 (where 10 is excellent) that respectively represent the quality of the service and the quality of the food at a restaurant, what should the tip be?
Let’s see how the formula will be affected now that we’ve added another variable. Suppose we try:
tip = 0.20/20*(service+food)+0.05;
0.25 0.2
tip
0.15 0.1 0.05 10 10 5 food 0 0 5 service
In this case, the results look pretty, but when you look at them closely, they don’t seem quite right. Suppose you want the service to be a more important
110
An Introductory Example: Fuzzy vs. NonFuzzy
factor than the food quality. Let’s say that the service will account for 80% of the overall tipping “grade” and the food will make up the other 20%. Try:
servRatio=0.8; tip=servRatio*(0.20/10*service+0.05) + ... (1–servRatio)*(0.20/10*food+0.05);
0.25 0.2
tip
0.15 0.1 0.05 10 10 5 food 0 0 5 service
The response is still somehow too uniformly linear. Suppose you want more of a flat response in the middle, i.e., you want to give a 15% tip in general, and will depart from this plateau only if the service is exceptionally good or bad. This, in turn, means that those nice linear mappings no longer apply. We can still salvage things by using a piecewise linear construction. Let’s return to the onedimensional problem of just considering the service. You can string together a simple conditional statement using breakpoints like this:
if service<3, tip=(0.10/3)*service+0.05; elseif service<7, tip=0.15; elseif service<=10, tip=(0.10/3)*(service–7)+0.15; end
111
05).10/3)*service+0..25 0.1 0.05)*servRatio + .15 0. tip=((0.05 0 2 4 service 6 8 10 If we extend this to two dimensions.10/3)*(service–7)+0.2 tip 0.20/10*food+0.05 10 10 5 food 0 0 5 service 112 .1 Introduction The plot looks like this.. (1–servRatio)*(0. tip=(0.25 0. tip=((0. end 0. where we take food into account again.05). something like this results: servRatio=0.. else. (1–servRatio)*(0. if service<3.15 0..15)*servRatio + .8..2 tip 0.1 0. 0.. (1–servRatio)*(0. elseif service<7.20/10*food+0.05).15)*servRatio + .20/10*food+0.
If service is poor or the food is rancid. we’ve just defined the rules for a fuzzy logic system. If food is rancid. then tip is average 3. things like: • How are the rules all combined? • How do I define mathematically what an “average” tip is? These are questions we provide detailed answers to in the next few chapters. we might add the following two rules: 4. then tip is cheap 2. Of course. The details of the method don’t really change much from problem to problem — the mechanics of fuzzy logic aren’t terribly complex. What matters is what 113 . If service is good. Moreover. If we wanted to include the food’s effect on the tip. And coincidentally.An Introductory Example: Fuzzy vs. If we make a list of what really matters in this problem. we might end up with the following rule descriptions: 1. leaving aside all the factors that could be arbitrary. we can combine the two different lists of rules into one tight list of three rules like so: 1. it’s even less apparent how the algorithm works to someone who didn’t witness the original design process. then tip is generous In fact. If service is good. If service is poor. then tip is generous The order in which the rules are presented here is arbitrary. NonFuzzy Wow! The plot looks good. If food is delicious. and it’s definitely not easy to modify this code in the future. then tip is cheap 2. for example?) we would have a complete fuzzy inference system. It was a little tricky to code this correctly. Now if we give mathematical meaning to the linguistic variables (what is an “average” tip. The Fuzzy Approach It would be nice if we could just capture the essentials of this problem. It doesn’t matter which rules come first. then tip is cheap 5. then tip is average 3. there’s a lot left to the methodology of fuzzy logic that we’re not mentioning right now. then tip is generous These three rules are the core of our solution. If service is excellent or food is delicious. but the function is surprisingly complicated. If service is excellent.
15 0. country to country. The notion of an average tip might change from day to day.1 0.1 Introduction we’ve shown in this preliminary exposition: fuzzy is adaptable. we were able to add two more rules to the bottom of the list that influenced the shape of the overall output without needing to undo what had already been done. The picture above was generated by the three rules above. it wasn’t very easy to interpret. On the other hand. Moreover. the fuzzy system is based on some “common sense” statements. The mechanics of how fuzzy inference works is explained “The Big Picture” on page 218. simple. and in “Fuzzy Inference Systems” on page 236. It worked. In the “Building Systems with the Fuzzy Logic Toolbox” on page 245. but it was something of a nuisance to derive. but the underlying logic is the same: if the service is good. 114 .2 tip 0. Also. the maintenance of the structure of the algorithm decouples along fairly clean lines. Some Observations Here are some observations about the example so far. 0. city to city. the subsequent modification was pretty easy. and easily applied.05 10 10 5 food 0 0 5 service Here is the picture associated with the fuzzy system that solves this problem. and once we wrote it down as code. by using fuzzy logic rules. “Foundations of Fuzzy Logic” on page 220. the entire tipping problem is worked through using the graphical tools in the Fuzzy Logic Toolbox. We found a piecewise linear relation that solved the problem. the tip should be average. In other words.25 0. You can recalibrate the method quickly by simply shifting the fuzzy set that defines average without rewriting the fuzzy rules.
tip is average elseif service<goodService. foodRange=greatFood–badFood. For example. here is the piecewise linear tipping problem slightly rewritten to make it more generic. we can fight this tendency to be obscure by adding still more comments. *service+lowTip)*servRatio + . What we’re doing here isn’t (shouldn’t be!) that complicated. but the medium is not on our side. serviceRange=greatService–badService. threatening eventually to obscure it completely. but there is a greater likelihood that recalibration will not be so quick and simple. (greatService–goodService))* ... It performs the same function as before. % Establish constants lowTip=0. as with all code. tipRange=highTip–lowTip. goodService=7.15... badService=0. % If service is excellent or food is delicious. (1–servRatio)*(tipRange/foodRange*food+lowTip). for creeping generality to render the algorithm more and more opaque.05.. greatService=10. tip is generous else. tip is cheap if service<okayService.. highTip=0. only now the constants can be easily changed. % If service is good.. 115 ..... badFood=0. averTip=0.An Introductory Example: Fuzzy vs. (service–goodService)+averTip)*servRatio + . okayService=3. greatFood=10. True. tip=(((highTip–averTip)/ . NonFuzzy You can do this sort of thing with lists of piecewise linear functions.25. or perhaps by trying to rewrite it in slightly more selfevident ways. % If service is poor or food is rancid. tip=averTip*servRatio + (1–servRatio)* . (tipRange/foodRange*food+lowTip). end Notice the tendency here. (1–servRatio)*(tipRange/foodRange*food+lowTip).. tip=(((averTip–lowTip)/(okayService–badService)) .
tip is cheap % If service is good. also have meaning to the machine. as with a fuzzy system. We all know that computers have the ability to make things hopelessly complex. But really the limitation is no longer the computer—it’s our mental model of what the computer is doing. fuzzy logic is really about reclaiming the middle ground and letting the machine work with our preferences rather than the other way around.1 Introduction The truly fascinating thing to notice is that if we remove everything except for three comments. Or think of it this way: by making the equations as simple as possible (linear) we make things simpler for the machine but more complicated for us. which is why it’s a very successful technique for bridging the gap between people and machines. It’s about time. what remain are exactly the fuzzy rules we wrote down before: % If service is poor or food is rancid. tip is average % If service is excellent or food is delicious. the comment is identical with the code. 116 . think how much more likely your code is to have comments! Fuzzy logic lets the language that’s clearest to you. high level comments. tip is generous If.
. . . 2118 . . . . . . . . . . . 249 Working with Simulink . . 2114 Glossary . . . . . . . . . . . . . . . . . . . 276 Fuzzy Clustering . . . . . . . . . . . . . 2104 StandAlone CCode Fuzzy Inference Engine . 220 Building Systems with the Fuzzy Logic Toolbox . . . . . . . . . . . . . 22 Foundations of Fuzzy Logic . . . . . 24 Fuzzy Inference Systems . . 262 SugenoType Fuzzy Inference . . . . . . . . . . . . . . . . . . . . . . . . 270 anfis and the ANFIS Editor GUI . . 2116 References . 229 Working from the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Tutorial The Big Picture . . . . . . . . .
service tip Rules if service is poor then tip is cheap if service is good then tip is average if service is excellent then tip is generous Input terms (interpret) Output terms (assign) is interpreted as {poor.. The diagram below is something like a roadmap for the fuzzy inference process.2 Tutorial The Big Picture We’ll start with a little motivation for where we are headed in this chapter. average. All rules are evaluated in parallel. based on some set of rules. The first three sections of this chapter are the most important—they move from 218 .. Before we can build a system that interprets rules. we need to define the range that the water’s temperature can be expected to vary over as well as what we mean by the word hot.. These are all things we’ll be discussing in the next several sections of the manual. The rules themselves are useful because they refer to variables and the adjectives that describe those variables. It shows the general description of a fuzzy system on the left and a specific fuzzy system (the tipping example from the Introduction) on the right. assigns values to the output vector. good.. The point of fuzzy logic is to map an input space to an output space. This chapter is designed to guide you through the fuzzy logic process step by step by providing an introduction to the theory and practice of fuzzy logic. generous} tip To summarize the concept of fuzzy inference depicted in this figure. If we want to talk about how hot the water is. fuzzy inference is a method that interprets the values in the input vector and. The General Case. excellent} service is assigned to be {cheap. we have to define all the terms we plan on using and the adjectives that describe them. Input Output A Specific Example. and the primary mechanism for doing this is a list of ifthen statements called rules. and the order of the rules is unimportant.
start here. these first three sections are the most crucial. you should consider reading this section just to become familiar with the fuzzy inference process as it is employed here.The Big Picture general to specific. • Building systems with the Fuzzy Logic Toolbox. • Fuzzy inference systems. If you’re already familiar with fuzzy logic. which explains the specific methods of fuzzy inference used in the Fuzzy Logic Toolbox. If you just want to get up to speed as quickly as possible. such as Simulink use. 219 . But from the point of view of getting to know the toolbox. and demonstrations. Since the field of fuzzy logic uses many terms that do not yet have standard interpretations. first introducing underlying ideas and then discussing implementation details specific to the toolbox. which goes into detail about how you build and edit a fuzzy system using this toolbox. you may want to skip this section. automatic rule generation. This introduces the graphical user interface tools available in the Fuzzy Logic Toolbox and guides you through the construction of a complete fuzzy inference system from start to finish. which is an introduction to the general concepts. After this there are sections that touch on a variety of topics. These three areas are • Foundations of fuzzy logic.
There is no thing that is both a day of the week and not a day of the week. Thursday. Another version runs like this: Of any subject. It can contain elements with only a partial degree of membership. Shoe Polish Monday Thursday Saturday Days of the week Liberty Butter Dorsal Fins We call this set a classical set because it’s been around for such a long time. It was Aristotle who first formulated the Law of the Excluded Middle. the set of days of the week unquestionably includes Monday. first consider what is meant by what we might call a classical set. —Bertrand Russell Fuzzy Sets Fuzzy logic starts with the concept of a fuzzy set. 220 . and Saturday. Everything falls into either one group or the other. one thing must be either asserted or denied.” This law demands that opposites. liberty. and so on. A fuzzy set is a set without a crisp. To understand what a fuzzy set is. Here is a restatement of the law with annotations: “Of any subject (say Monday).2 Tutorial Foundations of Fuzzy Logic Everything is vague to a degree you do not realize till you have tried to make it precise. A classical set is a container that wholly includes or wholly excludes any given element. and dorsal fins. which says X must either be in set A or in set notA. It just as unquestionably excludes butter. the two categories A and notA. should between them contain the entire universe. one thing (being a day of the week) must be either asserted or denied (I assert that Monday is a day of the week). clearly defined boundary. For example.
More than anything else. Fuzzy reasoning becomes valuable exactly when we’re talking about how people really perceive the concept “weekend” as opposed to a simpleminded classification useful for accounting purposes only. defining the weekend as “the period from Friday night or Saturday to Monday morning. How does it work? Reasoning in fuzzy logic is just a matter of generalizing the familiar yesno (Boolean) logic.Foundations of Fuzzy Logic Now consider the set of days comprising a weekend. The diagram below is one attempt at classifying the weekend days. But this is exactly the point. though: fence sitting is a part of life. Classical or “normal” sets wouldn’t tolerate this kind of thing. The tool that fuzzy reasoning gives is the ability to reply to a yesno question with a notquiteyesorno answer. Shoe Polish Monday Butter Days of the weekend Liberty Saturday Sunday Friday Thursday Dorsal Fins Most would agree that Saturday and Sunday belong. Human experience suggests something different. Even the dictionary is imprecise. If we give “true” the numerical value of 1 and 221 . because we’re starting to take individual perceptions and cultural background into account when we define what constitutes the weekend. but what about Friday? It “feels” like a part of the weekend. This is the kind of thing that humans do all the time (think how rarely you get a straight answer to a seemingly simple question) but it’s a rather new trick for computers. Of course we’re on tricky ground here. the truth of any statement becomes a matter of degree. Either you’re in or you’re out. Any statement can be fuzzy. the following statement lays the foundations for fuzzy logic: In fuzzy logic. but somehow it seems like it should be technically excluded. So in the diagram above Friday tries its best to sit on the fence.” We’re entering the realm where sharp edged yesno logic stops being helpful.
2 and 0. Twovalued logic has played a central role in the history of science since Aristotle first codified it. no. we’re saying that fuzzy logic also permits inbetween values like 0. If I ask the question “Is X a member of set A?” the answer might be yes.0 Thursday Friday Saturday Sunday Monday 0.0 1. X might have partial membership in A. but not quite as much as Saturday).2 Tutorial “false” the numerical value of 0. On the right is a plot that shows the truth value for weekendness if we are allowed to respond with fuzzy inbetween values.0 Thursday Friday Saturday Sunday Monday weekendness Days of the weekend twovalued membership Days of the weekend multivalued membership Technically. In other words. 1. but not completely) Q: Is Sunday a weekend day? A: 0. Below on the left is a plot that shows the truth values for “weekendness” if we are forced to respond with an absolute yes or no response. or any one of a thousand intermediate values in between. now consider a continuous scale time plot of weekendness shown below.8 (for the most part yes. For instance: Q: Is Saturday a weekend day? A: 1 (yes. or false) Q: Is Friday a weekend day? A: 0.0 weekendness 0. 222 . but the time has come for it to share the stage. or true) Q: Is Tuesday a weekend day? A: 0 (no. Multivalued logic stands in direct contrast to the more familiar concept of twovalued (or bivalent yesno) logic.95 (yes. the representation on the right is from the domain of multivalued logic (or multivalent logic).7453. To return to our example.
and while it may be useful to an accountant. We’ll discuss this in greater detail in the next section.0 weekendness 0. 223 . consider the question of seasons. and. It occurs exactly once a year.Foundations of Fuzzy Logic 1. Using the astronomical definitions for the season. it doesn’t really connect with our realworld experience of weekendness. we’re defining the degree to which any given instant belongs in the weekend rather than an entire day.0 1.0 Thursday Friday Saturday Sunday Monday weekendness Days of the weekend twovalued membership Days of the weekend multivalued membership By making the plot continuous. partake of the quality of weekendness and thus deserve partial membership in the fuzzy set of weekend moments. just as the second hand sweeps past 12. notice that at midnight on Friday. The curve that defines the weekendness of any instant in time is a function that maps the input space (time of the week) to the output space (weekendness). to a small degree. we get sharp boundaries as shown on the left in the figure on the next page. But what we experience as the seasons varies more or less continuously as shown on the right below (in temperate northern hemisphere climates). This is one way to define the weekend. In the plot on the left. parts of Thursday. Specifically it is known as a membership function. What season is it right now? In the northern hemisphere. summer officially begins at the exact moment in the earth’s orbit when the North Pole is pointed most directly toward the sun. the weekendness truth value jumps discontinuously from 0 to 1. The plot on the right shows a smoothly varying curve that accounts for the fact that all of Friday. in late June. As another example of fuzzy sets.0 Thursday Friday Saturday Sunday Monday 0.
and the word “tall” would correspond to a curve that defines the degree to which any person is tall.0 March June September Time of the year December March degree of membership 0. we might say all people taller than six feet are officially considered tall. One of the most commonly used examples of a fuzzy set is the set of tall people. But such a distinction is clearly absurd.0 March June September Time of the year December March Membership Functions A membership function (MF) is a curve that defines how each point in the input space is mapped to a membership value (or degree of membership) between 0 and 1. say from 3 feet to 9 feet. It may make sense to consider the set of all real numbers greater than six because numbers belong on an abstract plane. but when we want to talk about real people. the 224 .0 spring summer fall winter degree of membership 0. In this case the universe of discourse is all potential heights. The input space is sometimes referred to as the universe of discourse. then what is the right way to define the set of tall people? Much as with our plot of weekend days. If the set of tall people is given the welldefined (crisp) boundary of a classical set.0 spring summer fall winter 1.2 Tutorial 1. a fancy name for a simple concept. excellent! You must be taller than this line to be considered TALL But if the kind of distinction shown above is unworkable. it is unreasonable to call one person short and another one tall when they differ in height by the width of a hair.
This curve defines the transition from not tall to tall.0 degree of membership. but one is significantly less tall than the other.0 continuous membership function for TALL definitely a tall person (µ = 0. The function itself can be an arbitrary curve whose 225 . If I say “She’s tall. Similarly. The curve is known as a membership function and is often given the designation of µ.0) not tall (µ = 0. The outputaxis is a number known as the membership value between 0 and 1. µ 0.0 degree of membership.30) height Subjective interpretations and appropriate units are built right into fuzzy sets.0) 1. µ 0. the units are included in the curve. Both people are tall to some degree.95) really not very tall at all (µ = 0.Foundations of Fuzzy Logic figure below shows a smoothly varying curve that passes from nottall to tall.” the membership function “tall” should already take into account whether I’m referring to a sixyearold or a grown woman. Certainly it makes no sense to say “Is she tall in inches or in meters?” Membership Functions in the Fuzzy Logic Toolbox The only condition a membership function must really satisfy is that it must vary between 0 and 1.0 height sharpedged membership function for TALL tall (µ = 1. 1.
The trapezoidal membership function. then a fuzzy set A in X is defined as a set of ordered pairs: A = {x.25 0 0 2 4 6 trimf. P = [1 5 7 8] 8 10 trimf trapmf 226 . speed.5 0. µA(x)  x ∈ X} µA(x) is called the membership function (or MF) of x in A.5 0. The Fuzzy Logic Toolbox includes 11 builtin membership function types.2 Tutorial shape we can define as a function that suits us from the point of view of simplicity. trapmf. For detailed information on any of the membership functions mentioned below. If X is the universe of discourse and its elements are denoted by x. The membership function maps each element of X to a membership value between 0 and 1.75 0. and it has the function name trimf. A classical set might be expressed as A = {x  x > 6} A fuzzy set is an extension of a classical set. and efficiency. built from several basic functions: piecewise linear functions. The simplest membership functions are formed using straight lines. By convention. 1 0. the sigmoid curve. It’s nothing more than a collection of three points forming a triangle. turn to Chapter 3. all membership functions have the letters mf at the end of their names. the simplest is the triangular membership function. convenience. the Gaussian distribution function. P = [3 6 8] 8 10 1 0. Of these.75 0. “Reference” . in turn. and quadratic and cubic polynomial curves. These straight line membership functions have the advantage of simplicity.25 0 0 2 4 6 trapmf. These 11 functions are. has a flat top and really is just a truncated triangle curve.
e. P = [2 3 −5 8] 8 10 sigmf dsigmf psigmf Polynomial based curves account for several of the membership functions in the toolbox. dsigmf. The bell membership function has one more parameter than the Gaussian membership function. which are important in certain applications. P = [1 3 3 4] 8 10 1 0.25 0 0 2 4 6 gaussmf. P = [5 2 5 7] 8 10 1 0. The two functions are gaussmf and gauss2mf. Because of their smoothness and concise notation.75 0.5 0.75 0.75 0.5 0.25 0 0 2 4 6 gbellmf. Asymmetric and closed (i.25 0 0 2 4 6 dsigmf.25 0 0 2 4 6 sigmf.25 0 0 2 4 6 psigmf.25 0 0 2 4 6 gauss2mf. Gaussian and bell membership functions are popular methods for specifying fuzzy sets. Both of these curves have the advantage of being smooth and nonzero at all points. we also have the difference between two sigmoidal functions. 1 0. Next we define the sigmoidal membership function. 1 0.Foundations of Fuzzy Logic Two membership functions are built on the Gaussian distribution curve: a simple Gaussian curve and a twosided composite of two different Gaussian curves.75 0. S. P = [2 4] 8 10 1 0. P = [2 4 6] 8 10 gaussmf gauss2mf gbellmf Although the Gaussian membership functions and bell membership functions achieve smoothness.5 0. P = [2 5] 8 10 1 0. so it can approach a nonfuzzy set if the free parameter is tuned. The generalized bell membership function is specified by three parameters and has the function name gbellmf. so in addition to the basic sigmf. and Pi curves.5 0. and the product of two sigmoidal functions psigmf. all 227 . they are unable to specify asymmetric membership functions. which is either open left or right.75 0.5 0. Three related membership functions are the Z.5 0.75 0. not open to the left or right) membership functions can be synthesized using two sigmoidal functions.
1 0.75 0. On the other hand. for example the triangle and trapezoid functions. weekend days). (Friday is a weekend day to the degree 0.8). smf is the mirrorimage function that opens to the right. The selection is wide for those who want to explore the possibilities.25 0 0 2 4 6 smf. just remember that you could probably get along very well with just one or two types of membership functions.5 0.75 0.5 0. the weather is rather hot). but exotic membership functions are by no means required for perfectly good fuzzy inference systems. remember that more details are available on all these functions in the reference section.25 0 0 2 4 6 pimf. Logical Operations We now know what’s fuzzy about fuzzy logic. • A membership function associated with a given fuzzy set maps an input value to its appropriate membership value. In other words. Finally. Summary of Membership Functions • Fuzzy sets describe vague concepts (fast runner. if this list seems bewildering. but what about the logic? The most important thing to realize about fuzzy logical reasoning is the fact that it is a superset of standard Boolean logic. P = [3 7] 8 10 1 0. P = [1 8] 8 10 zmf pimf smf There’s a very wide selection to choose from when you’re selecting your favorite membership function. and pimf is zero on both extremes with a rise in the middle.25 0 0 2 4 6 zmf. which makes up the second half of this manual. P = [1 4 5 10] 8 10 1 0. (Friday is sort of a weekend day.75 0. if we keep the 228 .5 0. hot weather. • The degree an object belongs to a fuzzy set is denoted by a membership value between 0 and 1.2 Tutorial named because of their shape. • A fuzzy set admits the possibility of partial membership in it. And the Fuzzy Logic Toolbox also allows you to create your own membership functions if you find this list too restrictive. The function zmf is the asymmetrical polynomial curve open to the left.
Using the same reasoning. resolve the statement A AND B. standard logical operations will hold.B) A 1A 0 0 1 1 0 1 0 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 0 1 1 0 AND OR NOT Moreover. A B min(A.1). We’ve converted the truth table to a plot of two fuzzy sets applied together to create one fuzzy 229 . As an example.Foundations of Fuzzy Logic fuzzy values at their extremes of 1 (completely true). Finally. by using the function min(A. the operation NOT A becomes equivalent to the operation 1 – A . where A and B are limited to the range (0. Notice how the truth table above is completely unchanged by this substitution.B). how will these truth tables be altered? The input values can be real numbers between 0 and 1. That is. and 0 (completely false). we can replace the OR operation with the max function. consider the standard truth tables below: A B A and B A B A or B A not A 0 0 1 1 0 1 0 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 0 1 1 0 AND OR NOT Now remembering that in fuzzy logic the truth of any statement is a matter of degree. so that A OR B becomes equivalent to max(A. we can now consider values other than 1 and 0.B) A B max(A. since there is a function behind the truth table rather than just the truth table itself. The next figure uses a graph to show the same information.B). What function will preserve the results of the AND truth table (for example) and also extend to all real numbers between 0 and 1? One answer is the min operation.
µB(x)) 230 . The Fuzzy Logic Toolbox uses the classical operator for the fuzzy complement as shown above. we’re defining what are known as the fuzzy intersection or conjunction (AND). In general. Additional Fuzzy Operators We’ve only defined here one particular correspondence between twovalued and multivalued logical operations for AND. OR. The intersection of two fuzzy sets A and B is specified in general by a binary mapping T. A A B B A Twovalued logic A and B A or B not A A B A B A Multivalued logic A and B not A A or B AND min(A. these functions are arbitrary to a surprising degree. and NOT.B) NOT (1A) Given these three functions. This correspondence is by no means unique. OR. while the lower part of the figure displays how the operations work over a continuously varying range of truth values A and B according to the fuzzy operations we’ve defined. we can resolve any construction using fuzzy sets and the fuzzy logical operation AND. We have defined above what we’ll call the classical operators for these functions: AND = min. which aggregates two membership functions as follows: µA∩B(x) = T(µA(x). Typically most fuzzy logic applications make use of these operations and leave it at that. and NOT. and fuzzy complement (NOT). but also enables you to customize the AND and OR operators. however. In more general terms. The upper part of the figure displays plots corresponding to the twovalued truth tables above.2 Tutorial set. and NOT = additive complement. OR = max.B) OR max(A. fuzzy union or disjunction (OR).
such as those of Yager [Yag80]. ) satisfying: boundary: S(1. S(a. T(b. a) associativity: S(a. 0) = S(0. A Tconorm (or Snorm) operator is a binary mapping S( . and Sugeno [Sug77]. . The second requirement implies that a decrease in the membership values in A or B cannot produce an increase in the membership value in A intersection B. µB(x)) For example. Schweizer and Sklar [Sch63]. the fuzzy union operator is specified in general by a binary mapping S: µA∪B(x) = S(µA(x). These fuzzy intersection operators. 1) = T(1. which are often referred to as Tconorm (or Snorm) operators. which are usually referred to as Tnorm (Triangular norm) operators. c)) = T(T(a. c) Several parameterized Tnorms and dual Tconorms have been proposed in the past. b). ) satisfying: boundary: T(0. . the binary operator T may represent the multiplication of µ A ( x ) and µ B ( x ) .Foundations of Fuzzy Logic For example. b) = T(b. b) = S(b. . T(a. must satisfy the following basic requirements. d) if a <= c and b <= d commutativity: S(a. Like fuzzy intersection. 0) = 0. 231 . meet the following basic requirements. A Tnorm operator is a binary mapping T( . S(b. a) = a monotonicity: S(a. d) if a <= c and b <= d commutativity: T(a. The third requirement indicates that the operator is indifferent to the order of the fuzzy sets to be combined. . b) <= S(c. b). b) <= T(c. Finally. the binary operator S can represent the addition of µ A ( x ) and µ B ( x ). c)) = S(S(a. a) = a monotonicity: T(a. These fuzzy union operators. Each of these provides a way to vary the “gain” on the function so that it can be very restrictive or very permissive. the fourth requirement allows us to take the intersection of any number of sets in any order of pairwise groupings. 1) = 1. Dubois and Prade [Dub80]. a) associativity: T(a. c) The first requirement imposes the correct generalization to crisp sets.
In the ifthen rule. Interpreting an ifthen rule involves distinct parts: first evaluating the antecedent (which involves fuzzifying the input and applying any necessary fuzzy operators) and second applying that result to the consequent (known as implication). average is represented as a fuzzy set. average). A less confusing way of writing the rule would be if service == good then tip = average In general. the input to an ifthen rule is the current value for the input variable (in this case. this is the distinction between a relational test using “==” and a variable assignment using the “=” symbol. on page 241. respectively. On the other hand. and so the antecedent is an interpretation that returns a single number between 0 and 1. ifthen rules don’t present much difficulty.2 Tutorial IfThen Rules Fuzzy sets and fuzzy operators are the subjects and verbs of fuzzy logic. A single fuzzy ifthen rule assumes the form if x is A then y is B where A and B are linguistic values defined by fuzzy sets on the ranges (universes of discourse) X and Y. This set will later be defuzzified. and so the consequent is an assignment that assigns the entire fuzzy set B to the output variable y. how does this reflect on the conclusion? The answer is a simple one: 232 . In the case of twovalued or binary logic. the word “is” gets used in two entirely different ways depending on whether it appears in the antecedent or the consequent. If the premise is true. The ifpart of the rule “x is A” is called the antecedent or premise. then the conclusion is true. service) and the output is an entire fuzzy set (in this case. assigning one value to the output. In MATLAB terms. while the thenpart of the rule “y is B” is called the consequent or conclusion. The concept of defuzzification is described in the next section. If we relax the restrictions of twovalued logic and let the antecedent be a fuzzy statement. These ifthen rule statements are used to formulate the conditional statements that comprise fuzzy logic. An example of such a rule might be if service is good then tip is average Note that good is represented as a number between 0 and 1.
Both are supported by the Fuzzy Logic Toolbox. then the consequent is also true to that same degree. The implication function then modifies that fuzzy set to the degree specified by the antecedent.. in which case all parts of the antecedent are calculated simultaneously and resolved to a single number using the logical operators described in the preceding section. How is the consequent affected by the antecedent? The consequent specifies a fuzzy set be assigned to the output. 233 .Foundations of Fuzzy Logic if the antecedent is true to some degree of membership.5 p → 0. The most common ways to modify the output fuzzy set are truncation using the min function (where the fuzzy set is “chopped off” as shown below) or scaling using the prod function (where the output fuzzy set is “squashed”). The consequent of a rule can also have multiple parts: if temperature is cold then hot water valve is open and cold water valve is shut in which case all consequents are affected equally by the result of the antecedent. but we use truncation for the examples in this section.. In other words in binary logic: p → q (p and q are either both true or both false) in fuzzy logic: 0.5 q (partial antecedents provide partial implication) The antecedent of a rule can have multiple parts: if sky is gray and wind is strong and barometer is falling. then .
0 If ( 0. Apply OR operator (max) max(0. 234 .7 If ( 0.7 2.7. Fuzzify inputs delicious 0. This process is explained in detail in the next section. Apply implication operator (min) min(0. generous) tip (fuzzy) Summary of IfThen Rules Interpreting ifthen rules is a threepart process.0.0 ) then tip = generous 0.7 0.0 service (crisp) food (crisp) µ(service==excellent) = 0 .2 Tutorial Antecedent Consequent If service is excellent or excellent food is delicious 0.7 0.7 ) 0.7 0. 0.0 or µ(food==delicious) = 0 .7 generous then tip = generous 3.7) = 0.7 then tip = generous 1.
The next section shows how the whole process works from beginning to end for a particular type of fuzzy inference system called a Mamdani type. The consequent of a fuzzy rule assigns an entire fuzzy set to the output.e. 235 . This is the degree of support for the rule. Finally the resulting set is defuzzified. one rule by itself doesn’t do much good. What’s needed are two or more rules that can play off one another. then the output fuzzy set is truncated according to the implication method. If the antecedent is only partially true. The output of each rule is a fuzzy set.. If there is only one part to the antecedent. this is the degree of support for the rule. 2 Apply fuzzy operator to multiple part antecedents: If there are multiple parts to the antecedent. is assigned a value less than 1). apply fuzzy logic operators and resolve the antecedent to a single number between 0 and 1. In general. or resolved to a single number. (i. 3 Apply implication method: Use the degree of support for the entire rule to shape the output fuzzy set. The output fuzzy sets for each rule are then aggregated into a single output fuzzy set.Foundations of Fuzzy Logic 1 Fuzzify inputs: Resolve all fuzzy statements in the antecedent to a degree of membership between 0 and 1. This fuzzy set is represented by a membership function that is chosen to indicate the qualities of the consequent.
Although the inference process we describe in the next few sections differs somewhat from the methods described in the original paper. [Jan97. This is sometimes known as a singleton output membership function. Because of its multidisciplinary nature. The mapping then provides a basis from which decisions can be made. the basic idea is much the same. fuzzy logic operators. Mam75. Mamdanitype inference. we will try to be as clear as possible about the different terms introduced in this section. and computer vision. fuzzy logic controllers. The process of fuzzy inference involves all of the pieces that are described in the previous sections: membership functions. fuzzy inference systems are associated with a number of names. data classification.2 Tutorial Fuzzy Inference Systems Fuzzy inference is the process of formulating the mapping from a given input to an output using fuzzy logic. After the aggregation process. decision analysis. or patterns discerned. there is a fuzzy set for each output variable that needs defuzzification. and ifthen rules. It enhances the efficiency of the defuzzification process because it greatly simplifies the computation 236 . and simply (and ambiguously) fuzzy systems. to use a single spike as the output membership function rather than a distributed fuzzy set. Since the terms used to describe the various parts of the fuzzy inference process are far from standard. such as fuzzyrulebased systems. Sug85]. expert systems. and it can be thought of as a predefuzzified fuzzy set. It’s possible. There are two types of fuzzy inference systems that can be implemented in the Fuzzy Logic Toolbox: Mamdanitype and Sugenotype. Mamdani’s fuzzy inference method is the most commonly seen fuzzy methodology. Fuzzy inference systems have been successfully applied in fields such as automatic control. fuzzy associative memory. fuzzy modeling. fuzzy expert systems. Descriptions of these two types of fuzzy inference systems can be found in the references. These two types of inference systems vary somewhat in the way outputs are determined. as we have defined it for the Fuzzy Logic Toolbox. Mamdani’s effort was based on Lotfi Zadeh’s 1973 paper on fuzzy algorithms for complex systems and decision processes [Zad73]. expects the output membership functions to be fuzzy sets. Mamdani’s method was among the first control systems built using fuzzy set theory. and in many cases much more efficient. It was proposed in 1975 by Ebrahim Mamdani [Mam75] as an attempt to control a steam engine and boiler combination by synthesizing a set of linguistic control rules obtained from experienced human operators.
then tip is cheap. Sugenotype systems support this type of model. The parallel nature of the rules is one of the more important aspects of fuzzy logic systems. Σ The results of the rules are combined and distilled (defuzzified). Output Tip (525%) The inputs are crisp (nonfuzzy) numbers limited to a specific range. Instead of sharp switching between modes based on breakpoints. In the Fuzzy Logic Toolbox. These sometimes cryptic and odd names have very specific meaning that we’ll define carefully as we step through each of them in more detail below.Fuzzy Inference Systems required by the more general Mamdani method. 237 . Input 1 Service (010) Rule 2 If service is good. The result is a crisp (nonfuzzy) number. In general. All rules are evaluated in parallel using fuzzy reasoning. Reprise In this section we provide the same twoinput oneoutput threerule tipping problem that you saw in the introduction. we use the weighted average of a few data points. Information flows from left to right. and defuzzification. we will glide smoothly from regions where the system’s behavior is dominated by either one rule or another. Input 2 Food (010) Rule 3 If service is excellent or food is delicious. 1 output. Sugenotype systems can be used to model any inference system in which the output membership functions are either linear or constant. then tip is average. Dinner for Two. application of the fuzzy operator (AND or OR) in the antecedent. Rather than integrating across the twodimensional function to find the centroid. which finds the centroid of a twodimensional function. implication from the antecedent to the consequent. then tip is generous. from two inputs to a single output. The basic structure of this example is shown in the diagram below. aggregation of the consequents across the rules. only in more detail. there are five parts of the fuzzy inference process: fuzzification of the input variables. 3 rule system Rule 1 If service is poor or food is rancid. Dinner for two a 2 input.
(via its membership function). food is rancid. given our graphical definition of delicious.7.” In this case. service is good. and each of the rules depends on resolving the inputs into a number of different fuzzy linguistic sets: service is poor. we rated the food as an 8. the input is always a crisp numerical value limited to the universe of discourse of the input variable (in this case the interval between 0 and 10) and the output is a fuzzy degree of membership in the qualifying linguistic set (always the interval between 0 and 1). the inputs must be fuzzified according to each of these linguistic sets. Step 2. corresponds to µ = 0. each input is fuzzified over all the qualifying membership functions required by the rules. The example we’re using in this section is built on three rules. as the linguistic variable “delicious. Result of fuzzification food is delicious food = 8 input (The compliment to the chef would be “your food is delicious to the degree 0. we know the degree to which each part of the antecedent has been satisfied for each rule. This number will then be applied to the output function. 0. Fuzzify Inputs The first step is to take the inputs and determine the degree to which they belong to each of the appropriate fuzzy sets via membership functions.7 delicious 1. The input to the fuzzy operator is two or more 238 . Fuzzify inputs. If the antecedent of a given rule has more than one part.7 for the “delicious” membership function. food is delicious. the fuzzy operator is applied to obtain one number that represents the result of the antecedent for that rule. Apply Fuzzy Operator Once the inputs have been fuzzified. Fuzzification of the input amounts to either a table lookup or a function evaluation. Before the rules can be evaluated. and so on.”) In this manner. which.2 Tutorial Step 1. to what extent is the food really delicious? The figure below shows how well the food at our hypothetical restaurant (rated on a scale of 0 to 10) qualifies. In the Fuzzy Logic Toolbox. For example.
The two different pieces of the antecedent (service is excellent and food is delicious) yielded the fuzzy membership values 0. Generally this weight is 1 (as it is for this example) and so it has no effect at all on the implication process. Apply OR operator (max). The probabilistic OR method (also known as the algebraic sum) is calculated according to the equation probor(a. Shown below is an example of the OR operator max at work. and the probabilistic OR method probor.7 0. Two builtin OR methods are also supported: max (maximum). Fuzzify inputs.7 0. If we were using the probabilistic OR method. and the fuzzy operation for rule 3 is complete. Every rule has a weight (a number between 0 and 1). we must take care of the rule’s weight.ab In addition to these builtin methods. any number of welldefined methods can fill in for the AND operation or the OR operation.7. excellent 2. We’re evaluating the antecedent of the rule 3 for the tipping calculation. which is applied to the number given by the antecedent. Apply Implication Method Before applying the implication method. The fuzzy OR operator simply selects the maximum of the two values.0 and 0. From time to 239 .0 result of fuzzy operator food is delicious service = 3 food = 8 input 1 input 2 Step 3. As is described in the section on fuzzy logical operations.b) = a + b . two builtin AND methods are supported: min (minimum) and prod (product). The output is a single truth value. the result would still be 0. 0. 0.7 respectively. There will be more information on how to do this later. 1. In the Fuzzy Logic Toolbox.7 in this case. you can create your own methods for AND and OR by writing any function and setting that to be your method of choice.0 service is excellent or delicious 0.Fuzzy Inference Systems membership values from fuzzified input variables.
2. Apply Implication operator (min). Aggregation is the process by which the fuzzy sets that represent the outputs of each rule are combined into a single fuzzy set. Two builtin methods are supported. The consequent is reshaped using a function associated with the antecedent (a single number). excellent generous delicious If service is excellent or food is delicious then tip = generous result of implication service = 3 food = 8 input 1 input 2 Step 4. the rules must be combined in some manner in order to make a decision. defuzzification. the implication method is implemented. Aggregation only occurs once for each output variable. Implication is implemented for each rule. The output of the aggregation process is one fuzzy set for each output variable. Apply OR operator (max). which truncates the output fuzzy set.2 Tutorial time you may want to weight one rule relative to the others by changing its weight value to something other than 1. Once proper weighting has been assigned to each rule. Aggregate All Outputs Since decisions are based on the testing of all of the rules in an FIS. Fuzzify inputs. and they are the same functions that are used by the AND method: min (minimum). 240 . just prior to the fifth and final step. The input of the aggregation process is the list of truncated output functions returned by the implication process for each rule. A consequent is a fuzzy set represented by a membership function. which weights appropriately the linguistic characteristics that are attributed to it. and prod (product). Antecedent Consequent 1. and the output is a fuzzy set. 3. The input for the implication process is a single number given by the antecedent. which scales the output fuzzy set.
In the diagram below. the aggregate of a fuzzy set encompasses a range of output values.Fuzzy Inference Systems Notice that as long as the aggregation method is commutative (which it always should be). and so must be defuzzified in order to resolve a single output value from the set. 1. or aggregated. excellent delicious 0 generous 25% tip = generous 0 25% 4. However. Fuzzify inputs. If service is excellent or food is delicious then service = 3 food = 8 input 1 input 2 0 Result of aggregation 25% Step 5. 3. Three builtin methods are supported: max (maximum). into a single fuzzy set whose membership function assigns a weighting for every output (tip) value. the final desired output for each variable is generally a single number. and sum (simply the sum of each rule’s output set). then the order in which the rules are executed is unimportant. 241 . good If service is good rule 2 has no dependency on input 2 0 then 25% tip = average 0 25% 3. Apply aggregation method (max). probor (probabilistic or). all three rules have been placed together to show how the output of each rule is combined. 2. 1. As much as fuzziness helps the rule evaluation during the intermediate steps. Defuzzify The input for the defuzzification process is a fuzzy set (the aggregate output fuzzy set) and the output is a single number. If poor rancid 0 cheap 25% tip = cheap 0 25% service is poor or food is rancid then average 2. Apply fuzzy operation (OR = max). Apply implication method (min).
largest of maximum. Information flows through the fuzzy inference diagram as shown below. if and then Interpreting the Fuzzy Inference Diagram 2. and then down the rule outputs to finish in the lower right.7% Result of defuzzification The Fuzzy Inference Diagram The fuzzy inference diagram is the composite of all the smaller diagrams we’ve been looking at so far in this section. This is a very compact way of showing everything at once. There are five builtin methods supported: centroid. 1. which returns the center of area under the curve. 0 25% 5.2 Tutorial Perhaps the most popular defuzzification method is the centroid calculation. bisector. from linguistic variable fuzzification all the way through defuzzification of the aggregate output. It simultaneously displays all parts of the fuzzy inference process we’ve examined. 242 . tip = 16. middle of maximum (the average of the maximum value of the output set). then across each row. Defuzzify the aggregate output (centroid). and smallest of maximum. if and then input 1 input 2 output Notice how the flow proceeds up from the inputs in the lower left. or rule.
output Customization One of the primary goals of the Fuzzy Logic Toolbox is to have an open and easily modified fuzzy inference system structure. within the basic 243 . There’s a lot to see in a fuzzy inference diagram. 1.7% 0% 25% 5. you can easily see that the implication method is truncation with the min function. Thus. the Fuzzy Logic Toolbox is designed to give you as much freedom as possible. Defuzzify (centroid). 2. 1. And so on. Apply implication method (min). Apply fuzzy operation (OR = max). you can learn a lot about a system very quickly. The max function is being used for the fuzzy OR operation. good rule 2 has no dependency on input 2 0 If service is good 10 then 0% 25% tip = average 0% 25% 3. from this diagram with these particular inputs.Fuzzy Inference Systems Shown below is the real fullsize fuzzy inference diagram. 3. For instance. but once you become accustomed to it. Rule 3 (the bottommost row in the diagram shown opposite) is having the strongest influence on the output. Apply tip = generous aggregation method (max). 0 If poor rancid cheap 10 service is poor or 0 food is rancid 10 then 0% 25% tip = cheap 0% 25% average 2. The Rule Viewer described in “The Rule Viewer” on page 259 is a MATLAB implementation of the fuzzy inference diagram. 0 If excellent delicious generous 10 service is excellent or 0 10 food is delicious then 0% 25% 0% 25% 4. Fuzzify inputs. service = 3 food = 8 input 1 input 2 tip = 16.
you can substitute your own MATLAB functions for any of the default functions used in the five steps detailed above: you make your own membership functions. OR methods. AND methods. For example. 244 . aggregation methods. implication methods.2 Tutorial constraints of the process described here. to customize the fuzzy inference process for your application. The next section describes exactly how to build and implement a fuzzy inference system using the tools provided. and defuzzification methods.
only we’ll be building it using the graphical user interface (GUI) tools provided by the Fuzzy Logic Toolbox. from the Top Now we’re going to work through a similar tipping example. The ANFIS Editor GUI is discussed later in this chapter. in that changes you make to the FIS using one of them. the toolbox includes the graphical ANFIS Editor GUI. can affect what you see on any of the other open GUIs. and the Surface Viewer. the Membership Function Editor. in general it’s much easier to build a system graphically. which is used for building and analyzing Sugenotype adaptive neural fuzzy inference systems. In addition to these five primary GUIs. “SugenoType Fuzzy Inference” on page 286. Although it’s possible to use the Fuzzy Logic Toolbox by working strictly from the command line. and observing fuzzy inference systems in the Fuzzy Logic Toolbox: the Fuzzy Inference System or FIS Editor. There are five primary GUI tools for building. in the section. These GUIs are dynamically linked. You can have any or all of them open for any given system.Building Systems with the Fuzzy Logic Toolbox Building Systems with the Fuzzy Logic Toolbox Dinner for Two. the Rule Editor. editing. 245 . the Rule Viewer.
The Rule Editor is for editing the list of rules that defines the behavior of the system. The Membership Function Editor is used to define the shapes of all the membership functions associated with each variable. If the number of inputs is too large. or the number of membership functions is too big. the number of inputs may be limited by the available memory of your machine. then it may also be difficult to analyze the FIS using the other GUI tools. 246 .2 Tutorial FIS Editor Rule Editor Membership Function Editor Fuzzy Inference System Readonly tools Rule Viewer Surface Viewer The FIS Editor handles the high level issues for the system: How many input and output variables? What are their names? The Fuzzy Logic Toolbox doesn’t limit the number of inputs. However.
as opposed to editing. The General Case.. it can show (for example) which rules are active. Input Output A Specific Example. and the Rule Editor can all read and modify the FIS data.. the Membership Function Editor. This chapter began with an illustration similar to the one below describing the main parts of a fuzzy inference system. 247 . Used as a diagnostic. service tip The GUI Editors. Any one of them can read and write both to the workspace and to the disk (the readonly viewers can still exchange plots with the workspace and/or the disk).. the various GUI windows are aware of the existence of the others. The Rule Viewer is a MATLABbased display of the fuzzy inference diagram shown at the end of the last section.. but the Rule Viewer and the Surface Viewer do not modify the FIS data in any way. it generates and plots an output surface map for the system. good. The FIS Editor. generous} The Membership Function Editor The five primary GUIs can all interact and exchange information. and will. those changes are reflected in the rules shown in the Rule Editor.Building Systems with the Fuzzy Logic Toolbox The Rule Viewer and the Surface Viewer are used for looking at. only the one below shows how the three Editors fit together. Thus if the names of the membership functions are changed using the Membership Function Editor. update related windows. They are strictly readonly tools. average. The two Viewers examine the behavior of the entire system. if necessary. The FIS Editor Rules if service is poor then tip is cheap if service is good then tip is average if service is excellent then tip is generous The Rule Editor Input terms (interpret) Output terms (assign) service = {poor.. the FIS. or how individual membership function shapes are influencing the results. If more than one of these editors is open for a single system.. excellent} tip = {cheap. The Surface Viewer is used to display the dependency of one of the outputs on any one or two of the inputs—that is. For any fuzzy inference system. The editors for any number of different FIS systems may be open simultaneously. any or all of these five GUIs may be open.
2. what should the tip be? The starting point is to write down the three golden rules of tipping. If the service is excellent or the food is delicious. a generous tip is 25%. Given a number between 0 and 10 that represents the quality of service at a restaurant (where 10 is excellent). and a cheap tip is 5%. Now we know the rules. Let’s begin working with the GUI tools to construct a fuzzy inference system for this decision process. then tip is generous. It’s also useful to have a vague idea of what the tipping function should look like. and so on.S.5 Bad service or bad food Great service or great food Obviously the numbers and the shape of the curve are subject to local traditions. The Basic Tipping Problem. then tip is cheap. 3.2 Tutorial Getting Started We’ll start with a basic description of a twoinput. but the three rules are pretty universal. then tip is average. If the service is good.15 . . 10 is excellent).). oneoutput tipping problem (based on tipping practices in the U. 1. based on years of personal experience in restaurants. We’ll assume that an average tip is 15%. cultural bias. and we have an idea of what the output should look like. If the service is poor or the food is rancid.25 . and another number between 0 and 10 that represents the quality of the food at that restaurant (again. 248 .
you can load the already built system by typing fuzzy tipper This will load the FIS associated with the file tipper. The sample membership functions shown in the boxes are just icons and do not depict the actual shapes of the membership functions. such as the defuzzification method.. The following discussion walks you through building a new fuzzy inference system from scratch. open. to open the Membership Function Editor.fis (the . or edit a fuzzy system using any of the five basic GUI tools. If you want to save time and follow along quickly.Building Systems with the Fuzzy Logic Toolbox The FIS Editor These menu items allow you to save.. Doubleclick on the system diagram to open the Rule Editor. There’s a simple diagram at the top that shows the names of each input variable on the left. Doubleclick on the icon for the output variable. menu options. This status line describes the most recent operation. is what we’ve been describing so far and 249 . The default. It can be changed using one of the Save as. Below the diagram is the name of the system and the type of inference used. and those of each output variable on the right.fis is implied) and launch the FIS Editor. you will not be building rules and constructing membership functions. This edit field is used to name and edit the names of the input and output variable. Mamdanitype inference. tip. Doubleclick on an input variable icon to open the Membership Function Editor. The name of the system is displayed here. However. The FIS Editor displays general information about a fuzzy inference system. These popup menus are used to adjust the fuzzy inference functions. if you load the prebuilt system.
is also available. Our one output is tip. 5 Click once on the righthand (blue) box marked output1. 1 Click once on the lefthand (yellow) box marked input1 (the box will be highlighted in red). one output system. are the popup menus that allow you to modify the various pieces of the inference process. we will construct a twoinput. labeled input1. 4 In the white edit field on the right. Another slightly different type of inference. so go to the Edit menu and select Add input. and one output. change input1 to service and press Return. and its range. called Sugenotype inference.2 Tutorial what we’ll continue to use for this example. On the right side at the bottom of the figure is the area that displays the name of either an input or output variable. This method is explained in “SugenoType Fuzzy Inference” on page 286. change input2 to food and press Return. The generic untitled FIS Editor opens. on the left side of the figure. We’d like to change the variable names to reflect that. with one input. its associated membership function type. Below that region are the Help and Close buttons that call up online help and close the window. though. 250 . At the bottom is a status line that relays information about the system. labeled output1. To start this system from scratch. 3 Click once on the lefthand (yellow) box marked input2 (the box will be highlighted in red). type fuzzy at the MATLAB prompt. The latter two fields are specified only after the membership functions have been. 6 In the white edit field on the right. 2 In the white edit field on the right. The two inputs we will have in our example are service and food. change output1 to tip. respectively. Below the name of the fuzzy inference system. A second yellow box labeled input2 will appear. For this example.
Next define the membership functions associated with each of the variables. you also rename the entire system. Your window will look something like this. You’ve entered all the information you need for this particular GUI. You will see the diagram updated to reflect the new names of the input and output variables. Leave the inference options in the lower left in their default positions for now. 8 Enter the variable name tipper and click on OK. To do 251 . By saving to the workspace with a new name.Building Systems with the Fuzzy Logic Toolbox 7 From the File menu select Save to workspace as. There is now a new variable in the workspace called tipper that contains all the information about this system....
This graph field displays all the membership functions of the current variable. This popup menu lets you change the type of the current membership function. This status line describes the most recent operation. Drag your mouse to move or change the shape of a selected membership function. The Membership Function Editor is the tool that lets 252 .. This is the “Variable Palette” area. • Doubleclick on the icon for the output variable. The Membership Function Editor shares some features with the FIS Editor. type and numerical parameters. This edit field lets you change the numerical parameters for the current membership function. tip. • Type mfedit at the command line. or edit a fuzzy system using any of the five basic GUI tools. This edit field lets you change the name of the current membership function.2 Tutorial this. This edit field lets you set the display range of the current plot. open. Click on a line to select it and you can change any of its attributes. You can open the Membership Function Editor in one of three ways: • Pull down the View menu item and select Edit Membership Functions. including name.. These text fields display the name and type of the current variable. and Help and Close buttons. open the Membership Function Editor. Click on a variable here to make it current and edit its membership functions. The Membership Function Editor These menu items allow you to save.. status lines. In fact. all of the five basic GUI tools have similar menu options. This edit field lets you set the range of the current variable.
The selected membership function can also be tagged for dilation or contraction by clicking on the small square drag points on the membership function. and then drag the membership function from side to side. of the membership function. (such as poor. A new window will appear. The membership functions from the current variable are displayed in the main graph.. and choose Add MFs. and then dragging the function with the mouse toward the outside. for contraction. which allows you to select both the membership function type and the number of membership functions associated with the selected variable. for the variable. type.Building Systems with the Fuzzy Logic Toolbox you display and edit all of the membership functions associated with all of the input and output variables for the entire fuzzy inference system. This will affect the mathematical description of the quality associated with that membership function for a given variable. Below the Variable Palette is some information about the type and name of the current variable.To set up your membership functions associated with an input or an output variable for the FIS. Next select the Edit pulldown menu. for dilation. once it has been selected. The process of specifying the input membership functions for this two input tipper problem is as follows: 253 . and parameters (shape). This will change the parameters associated with that membership function. there are not yet any membership functions associated with the variables that you have just defined with the FIS Editor. On the upper left side of the graph area in the Membership Function Editor is a “Variable Palette” that lets you set the membership functions for a given variable. or toward the inside. There is a text field in this region that lets you change the limits of the current variable’s range (universe of discourse) and another that lets you set the limits of the current plot (which has no real effect on the system). select an FIS variable in this region by clicking on it. These membership functions can be manipulated in two ways.. In the lower right corner of the window are the controls that let you change the name. You can first use the mouse to select a particular membership function associated with a given variable quality. service). When you open the Membership Function Editor to work on a fuzzy inference system that does not already exist in the workspace..
Change the name of the curve to rancid. Reset the associated parameters if desired. either use the mouse. The default parameter listing for this curve is [0 0 1 3]. 5 Name the curve with the middle hump. either use the mouse. 9 Name the curve with the rightmost trapazoid. and then click on the membership function. The window below pops open. from the Edit menu. as described above. 8 Click once directly on the curve with the leftmost trapazoid. To adjust the shape of the membership function.. delicious. as described above. from the Edit menu and add two trapmf curves to the input variable food. To adjust the shape of the membership function.2 Tutorial 1 Select the input variable. food. and then click on the membership function. and reset the associated parameters if desired 254 .. The default parameter listing for this curve is [1. service. by clicking on it. 2 Select Add MFs. Set both the Range and the Display Range to the vector [0 10]. 7 Select Add MFs.. and the curve with the rightmost hump.5 0]. excellent. or type in a desired parameter change. or type in a desired parameter change.. 3 Use the pulldown tab to choose gaussmf for MF Type and 3 for Number of MFs. Change the name of the curve to poor. 6 Select the input variable. by doubleclicking on it. Set both the Range and the Display Range to the vector [0 10]. This adds three Gaussian curves to the input variable service 4 Click once on the curve with the leftmost hump. good.
To create the output variable membership functions. First. set the Range (and the Display Range) to [0 30]. Initially. but the output scale is going to be a tip between 5 and 25 percent. go to the View menu and select Edit rules.. Now that the variables have been named.. 255 . the average membership function will be [10 15 20]. use the Variable Palette on the left. tip. you’re ready to write down the rules. the cheap membership function will have the parameters [0 5 10]. Use triangular membership function types for the output.Building Systems with the Fuzzy Logic Toolbox Next you need to create the membership functions for the output variable. and the generous membership function will be [20 25 30]. or type ruleedit at the command line. Your system should look something like this. tip. To call up the Rule Editor. to cover the output range.. and the membership functions have appropriate shapes and names. The inputs ranged from 0 to 10. selecting the output variable.
and one connection item. by clicking on the appropriate button. The menu items allow you to save. by clicking on and selecting one item in each input variable box. or added. Based on the descriptions of the input and output variables defined with the FIS Editor. one item in each output box. Rules may be changed. similar to those in the FIS Editor and the Membership Function Editor. Choosing none as one of the variable qualities will exclude that variable from a given rule. Negate input or output statements in rules. This status line describes the most recent operation. Link input statements in rules. open. and the Close button closes the window. The Format popup menu is available from the Options pulldown menu from the top menu bar—this is used to set the format for the display.2 Tutorial The Rule Editor Input or output selection menus. 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. Constructing rules using the graphical Rule Editor interface is fairly selfevident. Choosing not under any variable name will negate the associated quality. 256 . or edit a fuzzy system using any of the five basic GUI tools. including the menu bar and the status line. The Rule Editor also has some familiar landmarks. deleted. the Rule Editor allows you to construct the rule statements automatically. The Help button gives some information about how the Rule Editor works.
the weights are assumed to be unity (1). first click on the rule to be changed. Follow a similar procedure to insert the second and third rules in the Rule Editor to get: 1. If (service is excellent) or (food is delicious) then (tip is generous) (1) To change a rule. If (service is good) then (tip is average) (1) 3. or. If (service not poor) or (food not rancid) then (tip is not cheap) (1) click not under each variable. Language can be set from under Options as well. in the Connection block • cheap. tip. The Format popup menu from the Options menu indicates that you’re looking at the verbose form of the rules. You can specify the weights by typing in a desired number between zero and one under the Weight: setting. (service==poor) => (tip=cheap) (1) 2. For example. To insert the first rule in the Rule Editor. If (service is poor) or (food is rancid) then (tip is cheap) (1) The numbers in the parentheses represent weights that can be applied to each rule if desired. If you do not specify them. You will see 1. The resulting rule is: 1. Next make the desired changes to that rule. select the following: • poor under the variable service • rancid under the variable food • the radio button. and then click on Change rule. to change the first rule to 1. and then click Change rule. Try changing it to symbolic. under the output variable.Building Systems with the Fuzzy Logic Toolbox Similarly. (service==good) => (tip=average) (1) 3. (service==excellent) => (tip=generous) (1) 257 . If (service is poor) or (food is rancid) then (tip is cheap) (1) 2. The Help button will bring up a MATLAB Help window.
the second column corresponds to the output variable.” If you change the format to indexed.” Since there is only one input for this system. in that the variables. making the system easier for you to interpret. 3 (1) : 1 This is the version that the machine deals with. the third column displays the weight applied to each rule. A literal interpretation of rule 1 is: “if input 1 is MF1 (the first membership function associated with input 1) then output 1 should be MF1 (the first membership function associated with output 1) with the weight 1. select View rules. and the fourth column is shorthand that indicates whether this is an OR (2) rule or an AND (1) rule. The whole point of naming variables descriptively is. The first column in this structure corresponds to the input variable. 258 . At this point. the next of the GUI tools we’ll look at.. This is exactly the purpose of the Rule Viewer.. membership functions. as always. It would be nice. Thus. if. The indexed format doesn’t even bother with the names of your variables.. then. 1 (1) : 1 2. 1. you’ll see an extremely compressed version of the rules that has squeezed all the language out. From the View menu. at this point. The numbers in the first two columns refer to the index number of the membership function. unless you have some special purpose in mind. and so on. The symbolic format doesn’t bother with the terms. to look at a fuzzy inference diagram like the one presented at the end of the previous section and verify that everything is behaving the way we think it should. the fuzzy inference system has been completely defined. the AND connective implied by the 1 in the last column is of no consequence. Obviously the functionality of your system doesn’t depend on how well you have named your variables and membership functions. 2 (1) : 1 3.2 Tutorial There is not much difference in the display really. since it doesn’t depend on terms like “if” and “then. it will probably be easier for you to stick with the verbose format. and the rules necessary to calculate tips are in place. but it’s slightly more language neutral.
Click on a rule to display it in the status bar. or the thenpart of each rule. the corresponding rule will be displayed at the bottom of the figure. The first two columns of plots (the six yellow plots) show the membership functions referenced by the antecedent. and generate a new output response. The menu items allow you to save. This edit field allows you to set the input explicitly. Notice that 259 .Building Systems with the Fuzzy Logic Toolbox The Rule Viewer Each column of plots (yellow) shows how the input variable is used in the rules. Each rule is a row of plots. The bottomright plot shows how the output of each rule is combined to make an aggregate output and then defuzzified. right. If you click once on a rule number. or the ifpart of each rule. This line provides a defuzzified value. up. The third column of plots (the three blue plots) shows the membership functions referenced by the consequent. Each row of plots represents one rule (here there are 3). The input values are shown here at the top. open. Slide this line to change your input values. This status line describes the most recent operation. or edit a fuzzy system using any of the five basic GUI tools. The three small plots across the top of the figure represent the antecedent and consequent of the first rule. This column of plots (blue) shows how the output variable is used in the rules. and each column is a variable. The Rule Viewer displays a roadmap of the whole fuzzy inference process. You see a single figure window with 10 small plots nested in it. or down with these buttons. Shift the plots left. It’s based on the fuzzy inference diagram described in the previous section.
that is. Where the index line representing service crosses the membership function line “service is poor” in the upper left plot will determine the degree to which rule one is activated. You can also just click and drag this line in order to change the input values. a new calculation is performed. (or after manually specifying the input). to the point where you have clicked.. This corresponds to the characterization of none for the variable food in the second rule.. The Rule Viewer also shows how the shape of certain membership functions influences the overall result. 260 . the entire span of the output set based on the entire span of the input set. it performs well (depending on how much screen space you devote to it) with up to 30 rules and as many as 6 or 7 variables. it presents a sort of micro view of the fuzzy inference system. The fourth plot in the third column of plots represents the aggregate weighted decision for the given inference system. and you open it by selecting View surface. In the lower right there is a text field into which you can enter specific input values. A yellow patch of color under the actual membership function curve is used to make the fuzzy membership value visually apparent. There are also the now familiar items like the status line and the menu bar. you need to open up the Surface Viewer. If we follow rule 1 across the top of the diagram. for example. The aggregation occurs down the third column. for a relatively small number of inputs and outputs. [9 8]. The defuzzified output value is shown by the thick line passing through the aggregate fuzzy set. but. from the View menu. In this sense. we can see the consequent “tip is cheap” has been truncated to exactly the same degree as the (composite) antecedent—this is the implication process in action. If you want to see the entire output surface of your system. and then click on input. This is the last of our five basic GUI tools in the Fuzzy Logic Toolbox.2 Tutorial under food. Since it plots every part of every rule. and you can see the whole fuzzy inference process take place. Each of the characterizations of each of the variables is specified with respect to the input index line in this manner. When you release the line. there is a plot which is blank. For the twoinput system. it can become unwieldy for particularly large systems. The Rule Viewer allows you to interpret the entire fuzzy inference process at once. The Rule Viewer shows one calculation at a time and in great detail. and the resultant aggregate plot is shown in the single plot to be found in the lower right corner of the plot field. This will move the red index line horizontally. you will enter an input vector. You can also adjust these input values by clicking anywhere on any of the three plots for each input. This decision will depend on the input values for the system.
and the Close button closes the window. This plot shows the output surface for any output of the system versus any one or two inputs to the system This popup menu lets you specify the displayed output variable. we start to encounter trouble displaying the results. These popup menus let you specify the one or two displayed input variables. and the plot comes up soon after the calculation is complete. This allows you to keep the calculation time reasonable for complex problems. Upon opening the Surface Viewer. These edit fields let you determine how densely to grid the input space. To change the xaxis or yaxis grid after the surface is 261 . The Help button gives some information about how the Surface Viewer works. When we move beyond three dimensions overall. Just below the popup menus are two text input fields that let you determine how many xaxis and yaxis grid lines you want to include. Use mouse to rotate the axes. the Surface Viewer is equipped with popup menus that let you select any two inputs and any one output for plotting. This status line describes the most recent operation. we are presented with a twodimensional curve that represents the mapping from service quality to tip amount. we can see the entire mapping in one plot. Since this is a oneinput oneoutput case. or edit a fuzzy system using any of the five basic GUI tools.Building Systems with the Fuzzy Logic Toolbox The Surface Viewer The menu items allow you to save. Pushing the Evaluate button initiates the calculation. Push this button when you’re ready to calculate and plot. Accordingly. open. as they generate threedimensional plots that MATLAB can adeptly manage. This edit field lets you set the input explicitly for inputs not specified in the surface plot. Twoinput oneoutput systems also work well.
Notice that for the tipping problem. you’re saving an ASCII text FIS file representation of that system with the file suffix . fuzzy logic may provide an appropriate tool for the solution. The Ref. you might say. In such a case the input would be a fourdimensional vector with NaNs holding the place of the varying inputs while numerical values would indicate those values that remain fixed. you’re creating a variable (whose name you choose) that will act as a MATLAB structure for the FIS system. but two of the inputs must be held constant since computer monitors cannot display a fivedimensional shape. Importing and Exporting from the GUI Tools When you save a fuzzy system to disk. This text file can be edited and modified and is simple to understand. “Why bother? I could have just drawn a quick lookup table and been done an hour ago!” However.2 Tutorial in view. 262 . and click on either Xgrids: or Ygrids:. An NaN is the IEEE symbol for “not a number. the output of the fuzzy system matches our original idea of the shape of the fuzzy mapping from service to tip fairly well. simply change the appropriate text field. FIS files and FIS structures represent the same system. to redraw the plot.” This concludes the quick walkthrough of each of the main GUI tools. Note: If you do not save your FIS to your disk.fis. Input: field is used in situations when there are more inputs required by the system than the surface is mapping. if you are interested in solving an entire class of similar decisionmaking problems. according to which text field you changed. The Surface Viewer can generate a threedimensional output surface where any two of the inputs vary. you will not be able to recover it for use in a new MATLAB session. given its ease with which a system can be quickly modified. In hindsight. but only save it to the MATLAB workspace. Suppose you have a fourinput oneoutput system and would like to see the output surface. When you save your fuzzy system to the MATLAB workspace. The Surface Viewer has a special capability that is very helpful in cases with two (or more) inputs and one output: you can actually grab the axes and reposition them to get a different threedimensional view on the data.
263 . 2 min(a. For example. The values these functions can take must be between 0 and 1.b) ans = 1 2 4]. similar to the min function. 4 Enter the vector of parameters you want to use to parameterize your customized membership function in the text box next to Parameter list. There is a limitation on customized membership functions in that they cannot use more than 16 parameters. 3 Enter your custom membership function Mfile name. 6 Select OK. or prod in MATLAB. as in a=[1 2. aggregation method. 2]. 2 Choose the Add Custom MF item in the Edit menu on the Membership Function Editor GUI. and defuzzification method functions you provide need to work in a similar way to max. 5 Give the custom membership function a name different from any other membership function name you will use in your FIS. the implication method does an element by element matrix operation. and depends on at most 16 parameters. The AND method. in the Mfile function name text box. 3 b=[2 2. That is. there are a few guidelines you need to follow. custmf. custmf.m. that takes values between 0 and 1. OR method. min. they must be able to operate down the columns of a matrix. To define a custom membership function named custmf: 1 Create an Mfile for a function. 2 2 Custom Membership Functions You can create your own membership functions using an Mfile.Building Systems with the Fuzzy Logic Toolbox Customizing Your Fuzzy System If you want to include customized functions as part of your use of the Fuzzy Logic Toolbox.
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(7) y(i)=params(7).m and loading it into the Membership Function Editor using the parameters of your choice. elseif x(i)<params(6) y(i)=params(6). else y(i)=0. that depends on eight parameters between 0 and 10. testmf1. You can try naming this file testmf1. 264 . function out = testmf1(x. elseif x(i)<params(5) y(i)=params(5). elseif x(i)<params(8) y(i)=params(8). elseif x(i)<params(4) y(i)=params(4). end end out=. elseif x(i)<params(3) y(i)=params(3).1*y'.2 Tutorial Here is some sample code for a custom membership function.
fis. alone does. You can access the various components of this structure by typing the component name after typing a.fis') MATLAB will respond with a = name: type: andMethod: orMethod: defuzzMethod: impMethod: aggMethod: input: output: rule: 'tipper' 'mamdani' 'min' 'max' 'centroid' 'min' 'max' [1x2 struct] [1x1 struct] [1x3 struct] The labels on the left of this listing represent the various components of the MATLAB structure associated with tipper. getfis(a) returns Name = tipper Type = mamdani 265 . type a.type for example.Working from the Command Line Working from the Command Line The tipping example system is one of many example fuzzy inference systems provided with the Fuzzy Logic Toolbox. MATLAB will respond with ans = mamdani The function getfis(a) returns almost the same structure information that typing a. type a = readfis('tipper. The FIS is always cast as a MATLAB structure. At the MATLAB command line. To load this system (rather than bothering with creating it from scratch).
field syntax also generates this information.Inlabels.'Inlabels') Similarly. Thus. For example. “Structures and Cell Arrays.1) The structure.'output'. It allows you to change any property of an FIS.'gratuity'). you cannot get information by typing a. There is also a function called setfis that acts as the reciprocal to getfis. if you wanted to change the name of this system. getfis(a.2 Tutorial NumInputs = 2 InLabels = service food NumOutputs = 1 OutLabels = tip NumRules = 3 AndMethod = min OrMethod = max ImpMethod = min AggMethod = max DefuzzMethod = centroid Notice that some of these fields are not part of the structure. a.input or a. you can obtain structure information using getfis in this manner. For more information on the syntax for MATLAB structures.” in Using MATLAB. type a. 266 .'name'.1.1) getfis(a. but you can get it by typing: getfis(a. For example.input(1).'input'. see Chapter 13.mf(1) The function getfis is loosely modeled on the Handle Graphics® function get.'input'.1) getfis(a. you could type a = setfis(a.'mf'.
and gensurf. If you want a little more insight into this FIS structure. This function is intended more for debugging than anything else. Once any of these GUIs has been opened.name = 'gratuity'. The 267 . but it shows all the information recorded in the FIS structure Since the variable. you can access any of the other GUIs using the pulldown menu rather than the command line. • fuzzy(a): brings up the FIS Editor • mfedit(a): brings up the Membership Function Editor • ruleedit(a): brings up the Rule Editor • ruleview(a): brings up the Rule Viewer • surfview(a): brings up the Surface Viewer If. a is a Sugenotype FIS.Working from the Command Line However. try showfis(a) This returns a printout listing all the information about a. then anfisedit(a) will bring up the ANFIS Editor GUI. you can call up any of the GUIs for the tipping system directly from the command line. since a is already a MATLAB structure. plotmf. Now the FIS structure a has been changed to reflect the new name. in addition. a. designates the fuzzy tipping system. you can set this information more simply by typing a. Any of the following will bring up the tipping system with the associated GUI. System Display Functions There are three functions designed to give you a highlevel view of your fuzzy inference system from the command line: plotfis.
the function plotmf plots all the membership functions associated with a given variable as follows: plotmf(a.'input'.1) returns 268 .2 Tutorial first of these displays the whole system as a block diagram much as it would appear on the FIS Editor. plotfis(a) After closing any open MATLAB figures or GUI windows.
4 0.'output'. if plotmf is called while either of these is open. or in an open MATLAB figure.6 0.2 0 0 1 2 3 4 5 service 6 7 8 9 10 plotmf(a.4 0.1) cheap 1 average generous 0.6 0.2 0 0 5 10 15 tip 20 25 30 These plots will appear in the Membership Function Editor GUI. 269 .8 Degree of membership 0.8 Degree of membership 0.Working from the Command Line poor 1 good excellent 0.
to build the tipping system entirely from the command line. The entry in column 1 is the index number for the membership function associated with input 1. The result is either a twodimensional curve. and each membership function has an index number. Note that when there are three or more inputs. addrule. For instance. Probably the trickiest part of this process is learning the shorthand that the fuzzy inference systems use for building rules. and addrule.5) This rule is turned into a structure according to the following logic: If there are m inputs to a system and n outputs. then the first m vector entries of the rule structure correspond to inputs 1 through m. has an index number. you would use the commands newfis. The entry in 270 . Each variable. This is accomplished using the command line function. addmf. as is described in the description of genfis in Chapter 3. or a threedimensional surface. input.2 Tutorial Finally. gensurf must be generated with all but two inputs fixed. gensurf(a) 25 20 tip 15 10 5 10 8 6 4 2 food 0 0 2 service 6 4 8 10 Building a System from Scratch It is possible to use the Fuzzy Logic Toolbox without bothering with the GUI tools at all. the function gensurf will plot any one or two inputs versus any one output of a given system. The rules are built from statements like this if input1 is MF1 or input2 is MF3 then output1 is MF2 (weight = 0. or output. addvar. “Reference” .
mf(3).input(2).name='cheap' a.input(1).mf(1). a.name='tip'.params=[10 15 20].mf(2). a.params=[7 9 10 12]. a. a.name='rancid'.params=[0 5 10]. a.mf(3).params=[2 0 1 3].input(1).output(1).input(1). a. a.name='delicious'.mf(1).input(1).mf(2).input(2). a.mf(1).range=[0 30].mf(1).input(2). a.output(1).mf(2).input(2).name='service'.input(2). a.name='food'. a.mf(2). a. 271 .5 5].params=[1. a. a.mf(3). a.type='trimf'.input(1).input(2).mf(3). a.mf(2).5 0]. And so on.mf(1).name='generous'.output(1).input(2).mf(1).range=[0 10].mf(2). a. Column m + n + 1 is the weight associated with that rule (typically 1) and column m + n + 2 specifies the connective used (where AND = 1 and OR = 2).output(1). a.params=[1.output(1). The next n columns work the same way for the outputs.input(1).mf(2).output(1). a. a.mf(1). a.type='trapmf'. The structure associated with the rule shown above is 1 3 2 0. a.output(1). a.params=[1.type='trimf'. a.mf(3).5 2 Here is one way you can build the entire tipping system from the command line.name='excellent'.input(1).name='poor'. a=newfis('tipper'). a.5 10].input(2).mf(1).output(1).input(1).mf(2).Working from the Command Line column 2 is the index number for the membership function associated with input 2.output(1).input(1).type='gaussmf'.type='gaussmf'.output(1).name='average'. a. a.mf(2).input(1).type='trapmf'.range=[0 10].type='gaussmf'.type='trimf'.mf(1).input(1). using the MATLAB structure syntax.name='good'. a.
a.connection=2 Alternatively.rule(1). a=addmf(a. a.5 0]).2.'output'.rule(3).consequent=[1].'average'.rule(2).'input'.'delicious'.weight=1.[0 5 10]).'cheap'.1. a.[7 9 10 12]). a=addmf(a. a.'input'.'excellent'.1.rule(3).5 5]).antecedent=[3 2].'output'.[0 30]).'service'. a. a.'gaussmf'.'input'.rule(1).'rancid'.weight=1.'trimf'. a.rule(1).2. a=addmf(a.antecedent=[2 0]. a=addvar(a. a=addmf(a. a..consequent=[2]. a=addmf(a.'trimf'.1. 1 1 1 1 2 2 0 2 1 1 3 2 3 1 2 ]. a=addmf(a.'generous'.'input'.[2 0 1 3]).consequent=[3]. a=addmf(a.'input'. 272 .connection=1.[1. here is how you can build the entire tipping system from the command line using Fuzzy Logic Toolbox commands.rule(2).1.5 10]).rule(2). a.rule(3).'input'.output(1).[10 15 20]).weight=1.[20 25 30]).'poor'.1.rule(1)..2 Tutorial a.'output'. a=newfis('tipper').'food'.'gaussmf'.connection=2.'gaussmf'.1.rule(2).'trapmf'.'trimf'.[1. ruleList=[ . a=addmf(a.ruleList). a.'output'.'tip'.[0 10]).mf(3).params=[20 25 30]. a=addmf(a.rule(3).1.antecedent=[1 1]. a.[0 10]).'input'.'trapmf'.'good'. a=addrule(a. a. a=addvar(a.[1.
evalfis([3 5.2184 7.7885 The FIS Structure The FIS structure is the MATLAB object that contains all the fuzzy inference system information. including variable names. 2 7]. evalfis([1 2]. “Working from the Command Line” on page 265). use the function evalfis. a = readfis('tipper').5586 This function can also be used for multiple collections of inputs.field syntax (see the section. membership function definitions. a) ans = 5. you get a tremendous boost in speed. You can also access the FIS structure information using the structure. For example. All the information for a given fuzzy inference system is contained in the FIS structure. and so 273 . a) ans = 12. [1 2]. the following script evaluates tipper at the input. By doing multiple evaluations at once. This structure is stored inside each GUI tool.Working from the Command Line FIS Evaluation To evaluate the output of a fuzzy system for a given input. since different input vectors are represented in different parts of the input structure. Access functions such as getfis and setfis make it easy to examine this structure.
AggMethod 11. DefuzzMethod 12. This structure can itself be thought of as a hierarchy of structures. Type 3. Inputs/Outputs 4.2 Tutorial on. InLabels 13. showfis(a) 1. OutLabels tipper mamdani [ 2 1 ] [ 3 2 ] 3 3 min max min max centroid service food tip 274 . 14. OrMethod 9. NumRules 7. NumInputMFs 5. AndMethod 8. ImpMethod 10. Name 2. as shown below. NumOutputMFs 6. as shown in the diagram below: input1 MFs input FIS name type andMethod orMethod defuzzMethod impMethod aggMethod input output rule name range mf name type params output name range mf input2 MFs name type params rules antecedent consequent weight connections output MFs name type params You can generate a listing of information on the FIS using the showfis command.
27. 34. 40. 22. InRange OutRange InMFLabels OutMFLabels InMFTypes OutMFTypes InMFParams OutMFParams Rule Antecedent Rule Consequent Rule Weigth Rule Connection [ 0 10 ] [ 0 10 ] [ 0 30 ] poor good excellent rancid delicious cheap average generous gaussmf gaussmf gaussmf trapmf trapmf trimf trimf trimf [ 1. 44. 42. 29. 32. 44. 30. 43.Working from the Command Line 15. 41. 36. 23. 35. 25. 37. 42. 43. 17. 26.5 10 0 0 ] [ 0 0 1 3 ] [ 7 9 10 10 ] [ 0 5 10 0 ] [ 10 15 20 0 ] [ 20 25 30 0 ] [ 1 1 ] [ 2 0 ] [ 3 2 ] 1 2 3 1 1 1 2 1 2 275 . 18. 20. 33. 19. 16. 42. 44. 38. 31.5 0 0 0 ] [ 1.5 5 0 0 ] [ 1. 28. 39. 43. 24. 43. 21. 42. 44.
The rules appear in “indexed” format in a . [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'. and rmmf. The functions readfis and writefis are used for reading and writing these files. addrule.fis. you can modify the FIS by editing its .2 Tutorial The list of command line functions associated with FIS construction include getfis. that changing one entry may oblige you to change another. however.fis text file.fis text file rather than using any of the GUIs. setfis. You should be aware.[1.5 5] MF3='excellent':'gaussmf'.[1.5 0] MF2='good':'gaussmf'. addmf. rmvar. If you prefer. Saving FIS Files on Disk A specialized text file format is used for saving fuzzy inference systems to a disk.5 10] [Input2] Name='food' Range=[0 10] NumMFs=2 276 . addvar. showfis.[1. if you delete a membership function using this method. Here is the file tipper. For example. you also need to make certain that any rules requiring this membership function are also deleted.
[7 9 10 10] [Output1] Name='tip' Range=[0 30] NumMFs=3 MF1='cheap':'trimf'. 2 (1) : 1 3 2.[20 25 30] [Rules] 1 1. 1 (1) : 2 2 0.[0 5 10] MF2='average':'trimf'.[0 0 1 3] MF2='delicious':'trapmf'. 3 (1) : 2 277 .[10 15 20] MF3='generous':'trimf'.Working from the Command Line MF1='rancid':'trapmf'.
You can change the valve controlling the water that flows in. but the outflow rate depends on the diameter of the outflow pipe (which is constant) and the pressure in the tank (which varies with the water level). the simulation software available from The MathWorks. An Example: Water Level Control Picture a tank with a pipe flowing in and a pipe flowing out. you’re ready to embed your system directly into a simulation. If (level is high) then (valve is close_fast) (1) One of the great advantages of the Fuzzy Logic Toolbox is the ability to take fuzzy systems directly into Simulink and test them out in a simulation environment. If (level is low) then (valve is open_fast) (1) 3. A first pass at writing a fuzzy controller for this system might be the following. 1. It 278 . A Simulink block diagram for this system is shown below. The system has some very nonlinear characteristics. A controller for the water level in the tank needs to know the current water level and it needs to be able to set the valve. Our controller’s input will be the water level error (desired water level minus actual water level) and its output will be the rate at which the valve is opening or closing. Once you’ve created your fuzzy system using the GUI tools or some other method. If (level is okay) then (valve is no_change) (1) 2.2 Tutorial Working with Simulink The Fuzzy Logic Toolbox is designed to work seamlessly with Simulink.
fis is loaded into the FIS structure tank. Typing sltank at the command line. At the same time.Working with Simulink contains a Simulink block called the Fuzzy Logic Controller block. the file tank. causes the system to appear. 279 . The Simulink block diagram for this system is sltank.
to slow down the valve movement when we get close to the right level. This is done by clicking on Start from the pulldown menu under Simulate. You can examine With all five rules in operations. This is seen from the plot below.8 0. the water level’s rate of change.6 1. The result looks like this 2 1. A PID controller does not have this capability.2 Tutorial Some experimentation shows that three rules are not sufficient.8 1. 4.6 0. If (level is good) and (rate is positive) then (valve is open_slow) (1) The demo.4 1.2 1 0. the step response by simulating this system.2 1 0.6 0. We can deal with this by setting the close_slow valve membership function to be slightly different from the open_slow setting.4 0. sltank is built with these five rules.6 1.4 0. If (level is good) and (rate is negative) then (valve is close_slow) (1) 5.8 0. since the water level tends to oscillate around the desired level.2 0 0 10 20 30 40 50 60 Time (second) 70 80 90 100 We need to add another input.4 1. 2 1.8 1. and clicking on the Comparison block.2 0 0 10 20 30 40 50 60 Time (second) 70 80 90 100 One interesting feature of the water tank system is that the tank empties much more slowly than it fills up because of the specific value of the outflow diameter pipe. The valve command versus the water level 280 .
1 0. and so on).Working with Simulink change rate (depicted as water) and the relative water level change (depicted as level) surface looks like this.5 1 Because the MATLAB technical computing environment supports so many tools (like the Control System Toolbox. 0.8 0. the Neural Network Toolbox.05 water −0. This Rule Viewer provides an animation of how the rules are fired during the 281 .6 0.1 −1 level −0.6 −0. the Rule Viewer opens when you start the Simulink simulation. For a demonstration of how the Rule Viewer can be used to interact with a Fuzzy Logic Controller block in a Simulink model. In this demo.5 0 0. If you look closely. you can see a slight asymmetry to the plot. you can. for example. easily make a comparison of a fuzzy controller versus a linear controller or a neural network controller.4 0.05 0 −0. the Nonlinear Control Design Blockset. type sltankrule This demo contains a block called the Fuzzy Controller With Rule Viewer block.2 valve 0 −0.8 0.4 −0.2 −0.
The windows that open when you simulate the sltankrule demo are depicted as follows: The Rule Viewer that opens during the simulation can be used to access the Membership Function Editor.2 Tutorial water tank simulation. (see “The Membership Function Editor” on page 252. or “The Rule Editor” on page 256. or any of the other GUIs. for more information). the Rule Editor. 282 .
which contains the Fuzzy Logic Controller block. Remember to save any changes you make to your FIS to the workspace before you restart the simulation. To do so. and several demo blocks.Working with Simulink For example. Building Your Own Fuzzy Simulink Models To build your own Simulink systems that use fuzzy logic. To access these blocks. select the Edit rules menu item under the View menu of the open Rule Viewer. you may want to open the Rule Editor to change one of your rules. You can also open the Simulink library called fuzblock. simply copy the Fuzzy Logic Controller block out of sltank (or any of the other Simulink demo systems available with the toolbox) and place it in your own block diagram. the Fuzzy Controller With Rule Viewer block. Now you can view or edit the rules for this Simulink model: It’s best if you stop the simulation prior to selecting any of these editors to change your FIS. type fuzblock 283 .
Doubleclick on the Fuzzy Controller With Rule Viewer block.mex.2 Tutorial at the MATLAB prompt. The following library appears: When you use these blocks. This function is itself based on the same algorithms as the function evalfis. and referred to by name in the dialog box associated with the Fuzzy Logic Controller block. make sure that the fuzzy inference system (FIS) structure corresponding to your fuzzy system is both in the MATLAB workspace. but it has been tailored to work optimally within the 284 . and the following appears: This block uses the zeroorder hold method for sampling. The Fuzzy Logic Controller block is a masked Simulink block based on the Sfunction sffis.
Working with Simulink
Simulink environment. For more descriptions of these, see fuzblock on page 327, and sffis on page 365.
285
2
Tutorial
SugenoType Fuzzy Inference
The fuzzy inference process we’ve been referring to so far is known as Mamdani’s fuzzy inference method. It’s the most commonly seen fuzzy methodology. In this section we discuss the socalled Sugeno, or TakagiSugenoKang method of fuzzy inference first introduced in 1985 [Sug85]. It is similar to the Mamdani method in many respects. In fact the first two parts of the fuzzy inference process, fuzzifying the inputs and applying the fuzzy operator, are exactly the same. The main difference between Mamdanitype of fuzzy inference and Sugenotype is that the output membership functions are only linear or constant for Sugenotype fuzzy inference. A typical fuzzy rule in a zeroorder Sugeno fuzzy model has the form if x is A and y is B then z = k where A and B are fuzzy sets in the antecedent, while k is a crisply defined constant in the consequent. When the output of each rule is a constant like this, the similarity with Mamdani’s method is striking. The only distinctions are the fact that all output membership functions are singleton spikes, and the implication and aggregation methods are fixed and can not be edited. The implication method is simply multiplication, and the aggregation operator just includes all of the singletons.
286
SugenoType Fuzzy Inference
1. Fuzzify inputs
2. Apply fuzzy operation (OR = max)
3. Apply implication method (min).
1.
If
poor
rancid
cheap
service is poor
or
food is rancid
then
tip = cheap
average
2.
good If service is good
rule 2 has no dependency on input 2
then
tip = average
3.
If
excellent delicious generous
4. Apply aggregation method (max).
service is excellent
or
food is delicious
then
tip = generous
service = 3
food = 8
input 1
input 2
output
tip = 16.3%
5. Defuzzify (weighted average)
The figure above shows the fuzzy tipping model developed in previous sections of this manual adapted for use as a zeroorder Sugeno system. Fortunately it is frequently the case that singleton output functions are completely sufficient for a given problem’s needs. As an example, the system tippersg.fis is the Sugenotype representation of the nowfamiliar tipping model. If you load the
287
2
Tutorial
system and plot its output surface, you will see it is almost the same as the Mamdani system we’ve been looking at.
a = readfis('tippersg'); gensurf(a)
20
tip
15
10
10 8 6 4 2 food 0 0 2 service 6 4 8 10
The more general firstorder Sugeno fuzzy model has rules of the form if x is A and y is B then z = p*x + q*y + r where A and B are fuzzy sets in the antecedent, while p, q, and r are all constants. The easiest way to visualize the firstorder system is to think of each rule as defining the location of a “moving singleton.” That is, the singleton output spikes can move around in a linear fashion in the output space, depending on what the input is. This also tends to make the system notation very compact and efficient. Higher order Sugeno fuzzy models are possible, but they introduce significant complexity with little obvious merit. Sugeno fuzzy models whose output membership functions are greater than first order are not supported by the Fuzzy Logic Toolbox. Because of the linear dependence of each rule on the system’s input variables, the Sugeno method is ideal for acting as an interpolating supervisor of multiple linear controllers that are to be applied, respectively, to different operating conditions of a dynamic nonlinear system. For example, the performance of an aircraft may change dramatically with altitude and Mach number. Linear controllers, though easy to compute and wellsuited to any given flight condition, must be updated regularly and smoothly to keep up with the changing state of the flight vehicle. A Sugeno fuzzy inference system is
288
1) Name = line1 Type = linear Params = –1 –1 getfis(fismat.1) Name = output NumMFs = 2 MFLabels = line1 line2 Range = [0 1] The output variable has two membership functions: getfis(fismat. Similarly. An Example: Two Lines To see a specific example of a system with linear output membership functions. these membership functions are linear functions of the input variable. fismat = readfis('sugeno1').'mf'.fis. it’s a natural and efficient gain scheduler.'mf'.'output'.'output'. The membership function line1 is defined by the equation output = (1)*input + (1) and the membership function line2 is defined by the equation output = (1)*input + (1) 289 .'output'.1.1. a Sugeno system is suited for modeling nonlinear systems by interpolating multiple linear models. consider the one input one output system stored in sugeno1.2) Name = line2 Type = linear Params = 1 –1 Further. getfis(fismat.SugenoType Fuzzy Inference extremely well suited to the task of smoothly interpolating the linear gains that would be applied across the input space.
2). showrule(fismat) ans = 1. plotmf(fismat. gensurf(fismat) 1 Degree of belief low high 0. you could build a fuzzy system that switches between several optimal linear controllers as a highly nonlinear system moves around in its operating space. while high refers to values greater than zero. the Sugeno system lends itself to the use of adaptive techniques for constructing fuzzy models.1.2 0 −5 −4 −3 −2 −1 0 input 1 2 3 4 5 4 3 output 2 1 0 −1 −5 −4 −3 −2 −1 0 input 1 2 3 4 5 This is just one example of how a Sugenotype system gives you the freedom to incorporate linear systems into your fuzzy systems. By extension.'input'.1). Conclusion Because it is a more compact and computationally efficient representation than a Mamdani system.1.4 0. The function gensurf shows how the overall fuzzy system output switches smoothly from the line called line1 to the line called line2.6 0. subplot(2. If (input is low) then (output is line1) (1) 2. These adaptive techniques can be used to customize the membership functions so that the fuzzy system best models the data.8 0. If (input is high) then (output is line2) (1) The function plotmf shows us that the membership function low generally refers to input values less than zero. 290 .2 Tutorial The input membership functions and rules define which of these output functions will be expressed and when.1) subplot(2.
• It’s wellsuited to mathematical analysis. 291 . • It has widespread acceptance. PID control). • It works well with linear techniques (e. Here are some final considerations about the two different methods: Advantages of the Sugeno method • It’s computationally efficient. Advantages of the Mamdani method • It’s intuitive.g. • It’s wellsuited to human input. It uses the centroid associated with all of the output membership functions of the Mamdani system. • It works well with optimization and adaptive techniques.SugenoType Fuzzy Inference Note on FIS Conversion: The MATLAB command line function mam2sug can be used to convert a Mamdani system into a Sugeno system (not necessarily with a single output) with constant output membership functions.. See Chapter 3 for details. • It has guaranteed continuity of the output surface.
Also. input membership function to rules. There will be some modeling situations in which you can’t just look at the data and discern what the membership functions should look like. we’ve only applied fuzzy inference to modeling systems whose rule structure is essentially predetermined by the user’s interpretation of the characteristics of the variables in the model. As you have seen from the other fuzzy inference GUIs. This is where the socalled neuroadaptive learning techniques incorporated into anfis in the Fuzzy Logic Toolbox can help. 292 . the shape of the membership functions depends on parameters. These tools apply fuzzy inference techniques to data modeling. and changing these parameters will change the shape of the membership function. A Modeling Scenario Suppose you want to apply fuzzy inference to a system for which you already have a collection of input/output data that you would like to use for modeling. and the output membership function to a singlevalued output or a decision associated with the output. You don’t necessarily have a predetermined model structure based on characteristics of variables in your system. and somewhat arbitrarily chosen. Rather than choosing the parameters associated with a given membership function arbitrarily.2 Tutorial anfis and the ANFIS Editor GUI The basic structure of the type of fuzzy inference system that we’ve seen thus far is a model that maps input characteristics to input membership functions. we will see how membership function parameters can be chosen automatically using these Fuzzy Logic Toolbox applications. In this section we discuss the use of the function anfis and the ANFIS Editor GUI in the Fuzzy Logic Toolbox. or some similar scenario. these parameters could be chosen so as to tailor the membership functions to the input/output data in order to account for these types of variations in the data values. Instead of just looking at the data to choose the membership function parameters. modelfollowing. rules to a set of output characteristics. We have only considered membership functions that have been fixed. output characteristics to output membership functions.
Using a given input/output data set. anfis uses either back propagation or a combination of least squares estimation and backpropagation for membership function parameter estimation. which maps inputs through input membership functions and associated parameters. The computation of these parameters (or their adjustment) is facilitated by a gradient vector. until we distinguish them through the description of the GUI. What Is ANFIS? The acronym ANFIS derives its name from adaptive neurofuzzy inference system. Since the functionality of the command line function anfis and the ANFIS Editor GUI is similar. 293 . These techniques provide a method for the fuzzy modeling procedure to learn information about a data set. Once the gradient vector is obtained.anfis and the ANFIS Editor GUI Model Learning and Inference Through ANFIS The basic idea behind these neuroadaptive learning techniques is very simple. in order to compute the membership function parameters that best allow the associated fuzzy inference system to track the given input/output data. The Fuzzy Logic Toolbox function that accomplishes this membership function parameter adjustment is called anfis. can be used to interpret the input/output map. or through the ANFIS Editor GUI. The parameters associated with the membership functions will change through the learning process. anfis can be accessed either from the command line. the toolbox function anfis constructs a fuzzy inference system (FIS) whose membership function parameters are tuned (adjusted) using either a backpropagation algorithm alone. or in combination with a least squares type of method. This learning method works similarly to that of neural networks. and then through output membership functions and associated parameters to outputs. which provides a measure of how well the fuzzy inference system is modeling the input/output data for a given set of parameters. FIS Structure and Parameter Adjustment A networktype structure similar to that of a neural network. they are used somewhat interchangeably in this discussion. any of several optimization routines could be applied in order to adjust the parameters so as to reduce some error measure (usually defined by the sum of the squared difference between actual and desired outputs). This allows your fuzzy systems to learn from the data they are modeling.
to see how well the FIS model predicts the corresponding data set output values. the FIS model is selected to have parameters associated with the minimum checking data model error. so the process of selecting a data set for checking or testing purposes is made easier. data is collected using noisy measurements.2 Tutorial Familiarity Breeds Validation: Know Your Data The modeling approach used by anfis is similar to many system identification techniques. Next. this type of modeling works well if the training data presented to anfis for training (estimating) membership function parameters is fully representative of the features of the data that the trained FIS is intended to model. You can then use anfis to train the FIS model to emulate the training data presented to it by modifying the membership function parameters according to a chosen error criterion. However. This is not always the case. however. First. If you have collected a large amount of data. hopefully this data contains all the necessary representative features. One problem with model validation for models constructed using adaptive techniques is selecting a data set that is both representative of the data the trained model is intended to emulate. are presented to the trained FIS model. Model Validation Using Checking and Testing Data Sets Model validation is the process by which the input vectors from input/output data sets on which the FIS was not trained. yet sufficiently distinct from the training data set so as not to render the validation process trivial. and its use is described in a subsection that follows. This is where model validation comes into play. This other type of validation data set is referred to as the checking data set and this set is used to control the potential for the model overfitting the data. In general. if you expect to be presenting noisy measurements to your model. This is accomplished with the ANFIS Editor GUI using the socalled testing data set. In some cases. you collect input/output data in a form that will be usable by anfis for training. and the training data cannot be representative of all the features of the data that will be presented to the model. you hypothesize a parameterized model structure (relating inputs to membership functions to rules to outputs to membership functions. it’s possible the training data set does not include all of the representative features you want to model. 294 . When checking data is presented to anfis as well as training data. and so on). You can also use another type of data set for model validation in anfis.
Moreover. and these must be: • First or zeroth order Sugenotype systems • Single output. This example illustrates of the use of the ANFIS Editor GUI with checking data to reduce the effect of model overfitting. By examining the checking error sequence over the training period. and is not available for all of the fuzzy inference system options. you cannot make your own membership functions and defuzzification functions. you’ll have to use the ones provided.anfis and the ANFIS Editor GUI The basic idea behind using a checking data set for model validation is that after a certain point in the training. The ANFIS Editor GUI To get started with the ANFIS Editor GUI. the model error for the checking data set tends to decrease as the training takes place up to the point that overfitting begins. That is. but the checking data set is corrupted by a small amount of noise. This example illustrates the use of the ANFIS Editor GUI to compare data sets. anfis cannot accept all the customization options that basic fuzzy inference allows. two similar data sets are used for checking and training. anfis only supports Sugenotype systems. a training data set that is presented to anfis is sufficiently different than the applied checking data set. In the second example. and then the model error for the checking data suddenly increases. it is clear that the checking data set is not good for model validation purposes. 295 . Some Constraints of anfis anfis is much more complex than the fuzzy inference systems discussed so far. In the first example in the following section. obtained using weighted average defuzzification (linear or constant output membership functions) • Of unity weight for each rule An error occurs if your FIS structure does not comply with these constraints. type anfisedit The following GUI will appear on your screen. In principle. Specifically. the model begins overfitting the training data set.
testing. Plot region Status of the number of inputs.. From this GUI you can • Load data (training. The loaded data is plotted on the plot region. Clear Data unloads the data set selected under Type: and clears the plot region. Undo Open or edit a FIS with any of the other GUIs. Data appears in the plot region.. Train FIS after setting optimization method. The plot appears in the plot region. testing. outputs. this button allows you to open a graphical representation of its input/output structure. or load demo data.. error tolerance. Load FIS or generate FIS from loaded data using your chosen number of MFs and rules or fuzzy. • Generate an initial FIS model or load an initial FIS model using the options in the Generate FIS portion of the GUI • View the FIS model structure once an initial FIS has been generated or loaded by selecting the Structure button 296 . and number of epochs. Training data appears on the plot in blue as o o Checking data appears on the plot in blue as ++ FIS output appears on the plot in red as ** After you generate or load a FIS.2 Tutorial Load or save a fuzzy Sugeno system. input membership functions. Test data against the FIS model. or checking data from disk or workspace. This generates error plots in the plot region. and checking) by selecting appropriate radio buttons in the Load data portion of the GUI and then selecting Load Data. and output membership functions Testing data appears on the plot in blue as . Load either training. or open new Sugeno system.
first you need to have a training data set that contains desired input/output data pairs of the target system to be modeled. open a new Sugeno system. As we mentioned previously. or testing data output by selecting the Test Now button This function plots the test data against the FIS output in the plot region. Data Formalities and the ANFIS Editor GUI: Checking and Training To start training an FIS using either anfis or the ANFIS Editor GUI. These issues are discussed later in an example. (or that is applied to the command line function anfis) must be a matrix with the input data arranged as vectors in all but the last column. You can also use the ANFIS Editor GUI menu bar to load an FIS training initialization. Usually these training and checking data sets are collected based on observations of the target system and are then stored in separate files. Note on Data Format: Any data set you load into the ANFIS Editor GUI. and choosing the membership function parameters to be those associated with the minimum checking error if these errors indicate model overfitting. checking.anfis and the ANFIS Editor GUI • Choose the FIS model parameter optimization method: backpropagation or a mixture of backpropagation and least squares (hybrid method) • Choose the number of training epochs and the training error tolerance • Train the FIS model by selecting the Train Now button This training adjusts the membership function parameters and plots the training (and/or checking data) error plot(s) in the plot region. and/or a checking data set that helps with model overfitting during the training. • View the FIS model output versus the training. The use of a testing data set and a checking data set for model validation is discussed in “Model Validation Using Checking and Testing Data Sets” on page 294. overfitting is accounted for by testing the FIS trained on the training data against the checking data. Sometimes you also want to have the optional testing data set that can check the generalization capability of the resulting fuzzy inference system. 297 . You will have to examine your training error plots fairly closely in order to determine this. save your trained FIS. or open any of the other GUIs to interpret the trained FIS model. The output data must be in the last column.
type load load load load fuzex1trnData. You may also substitute your own data sets. Open the ANFIS Editor GUI by typing anfisedit..dat fuzex1chkData. directly. To load the training data set. The small GUI window that pops up allows you to type in a variable name from the workspace. 298 . Loading Data To work both of the following examples. Note on loading data: You may also want to load your data set from the fuzzydemos or any other directory on the disk.. only the checking data set is corrupted by noise.dat fuzex2trnData. click on Training.. To load these data sets from the directory fuzzydemos into the MATLAB workspace. worksp. using the ANFIS Editor GUI. you load the training data sets (fuzex1trnData and fuzex2trnData) and the checking data sets (fuzex1chkData and fuzex2chkData).2 Tutorial ANFIS Editor GUI Example 1: Checking Data Helps Model Validation In this section we look at an example that loads similar training and checking data sets.dat fuzex2chkData.dat from the command line. Type in fuzex1trnData. and then Load Data. into the ANFIS Editor GUI from the workspace. as shown below.
Next click on Checking in the Type column of the Load 299 .anfis and the ANFIS Editor GUI The training data appears in the plot in the center of the GUI as a set of circles. This index indicates the row from which that input data value was obtained (whether or not the input is a vector or a scalar). Notice the horizontal axis is marked data set index.
the default partitioning method.2 Tutorial data portion of the GUI to load fuzex1chkData from the workspace. (The two partition methods. grid partitioning and subtractive clustering. +++ Checking data ooo Training data This data set will be used to train a fuzzy system by adjusting the membership function parameters that best model this data. are described later in 2100 . Initializing and Generating Your FIS You can either initialize the FIS parameters to your own preference. Automatic FIS Structure Generation with ANFIS To initialize your FIS using anfis: 1 Choose Grid partition. This data appears in the GUI plot as plusses superimposed on the training data. The next step is to specify an initial fuzzy inference system for anfis to train. or if you do not have any preference for how you want the initial membership functions to be parameterized. you can let anfis do this for you.
A command line language example illustrating the use of genfis1 and anfis is provided later. Notice there are only two choices for the output membership function: constant and linear. This brings up a menu from which you can choose the number of membership functions. and the type of input and output membership functions. and in “Subtractive Clustering” on page 2123. You can also implement this FIS generation from the command line using the command genfis1 (for grid partitioning) or genfis2 (for subtractive clustering). 3 Fill in the entries as we’ve done below. you can choose your own preferred membership functions with specific parameters to be used by anfis as an initial FIS for training. MFs. 2 Click on the Generate FIS button. This limitation of output membership function choices is because anfis only operates on Sugenotype systems.anfis and the ANFIS Editor GUI “Fuzzy CMeans Clustering” on page 2120. and click on OK. Specifying Your Own Membership Functions for ANFIS Although we don’t expect you to do this for this example. 2101 .
or Load from disk. 5 Use the View menu to return to the ANFIS Editor GUI to train the FIS.2 Tutorial To define your own FIS structure and parameters: 1 Open the Edit membership functions menu item from the View menu. 2 Add your desired membership functions (the custom membership option will be disabled for anfis). click on Load from worksp. Either of these radio buttons toggle the Generate FIS button to Load. Name your FIS.. see “The FIS Editor” on page 249 and “The Membership Function Editor” on page 252. in the Generate FIS portion of the GUI. To load an existing FIS for ANFIS initialization. 4 Select the Edit FIS properties menu item from the View menu. For carrying out this and the following step. Otherwise you will be loading your FIS from the workspace. Use the Rule Editor to generate the rules (see“The Rule Editor” on page 256).. 3 Select the Edit rules menu item in the View menu. The output membership functions must either be all constant or all linear.. Load your FIS by clicking on this button. and save it to either the workspace or the disk. You will load your FIS from the disk if you have saved an FIS previously that you would like to use. 2102 .
you can view the model structure by clicking on the Structure button in the middle of the righthand side of the GUI.for example. leftmost node is the input node Node representing a normalization factor for the rules. A new GUI appears. You can view the membership functions or the rules by opening either the Membership Function Editor. or or. The branches in this nodal graph are color coded to indicate whether or not and. Clicking on the nodes indicates information about the structure. are used in the rules. or the Rule Editor from the View menu. 2103 .anfis and the ANFIS Editor GUI Viewing Your FIS Structure After you generate the FIS. as follows: Return to other open GUIs using the Window menu. not. Color coding of branches characterizes the rules. Node labels .
• Select Train Now.2 Tutorial ANFIS Training The two anfis parameter optimization method options available for FIS training are hybrid (the default. mixed least squares and backpropagation) and backpropa (backpropagation).. The Error Tolerance is used to create a training stopping criterion. This is best left set to 0 if you don’t know how your training error is going to behave. To start the training: • Leave the optimization method at hybrid. under the Epochs listing on the GUI (the default value is 3). The following should appear on your screen: *** Training error . which is related to the error size. anfis chooses the model parameters associated with the minimum checking 2104 . This increase represents the point of model overfitting.. Checking error Notice how the checking error decreases up to a certain point in the training and then it increases. The training will stop after the training data error remains within this tolerance. • Set the number of training epochs to 40.
Testing Your Data Against the Trained FIS To test your FIS against the checking data. 2105 . you must make sure that the newly loaded data sets have the same number of inputs as the previously loaded ones did. and click on Test Now. Otherwise you will have to start a new anfisedit session from the command line. This is an example for which the checking data option of anfis is useful. Now when you test the checking data against the FIS it looks pretty good: Note on loading more data with anfis: If you are ever loading data into anfis after clearing previously loaded data.anfis and the ANFIS Editor GUI error (just prior to this jump point). click on Checking data in the Test FIS portion of the GUI.
don’t load any checking data before you train the FIS. The other method you can use is to close the GUI and go to the command line and retype anfisedit. If you decide to retrain your FIS with no checking data. the training data and checking data) from the MATLAB workspace just as you did in the previous example. although you don’t have to. 2106 . In this case you will have to reload the training data. One method is to click on the Checking radio button in the Load data portion of the GUI and then click on Clear Data to unload the checking data. we examine what happens when the training and checking data sets are sufficiently different. 1 Clear both the training and checking data. you can unload the checking data in one of two ways. We see how the ANFIS Editor GUI can be used to learn something about data sets and how they differ. ANFIS Editor GUI Example 2: Checking Data Doesn’t Validate Model In this example. After clearing the data. Once the FIS is generated you can use your first training experience to decide on the number of training epochs you want for the second round of training.2 Tutorial Note on the Checking Data option and Clearing Data: If you don’t want to use the checking data option of anfis. you will need to regenerate your FIS. 2 You can press the Clear Plot button on the right. 3 Load fuzex2trnData and fuzex2chkData (respectively.
anfis and the ANFIS Editor GUI You should get something that looks like this: +++ Checking data ooo Training data 2107 .
When this is not the case.2 Tutorial Train the FIS for this system exactly as you did in the previous example.. the checking error is sufficiently large to indicate that either more data needs to be selected for training. It appears that the minimum checking error occurs within the first epoch. In this example. You should get the following: *** Training error . What’s wrong here? This example illustrates the problem discussed earlier wherein the checking data set presented to anfis for training was sufficiently different from the training data set. Otherwise the system can 2108 . As a result. except now choose 60 Epochs before training. the trained FIS did not capture the features of this data set very well. you can analyze the checking error plots to see whether or not the checking data performed sufficiently well with the trained model. Checking error Notice the checking error is quite large. This illustrates the importance of knowing the features of your data set well enough when you select your training and checking data.. Recall that using the checking data option with anfis automatically sets the FIS parameters to be those associated with the minimum checking error. or you may want to modify your membership function choices (both the number of membership functions and the type). Clearly this set of membership functions would not be the best choice for modeling the training data.
In this section we describe how to carry out the command line features of anfis on a chaotic timesseries prediction example. Otherwise you need to retrain the FIS. generating an FIS using the ANFIS Editor GUI is quite simple. You must check that the checking data error does what is supposed to. To complete this example. To do so. However. The following plot in the GUI indicates that there is quite a discrepancy between the checking data output and the FIS output. and click on Test Now. as you saw in the last example. you need to be cautious about implementing the checking data validation feature of anfis. 2109 . let’s test the trained FIS model against the checking data.anfis and the ANFIS Editor GUI be retrained without the checking data. if you think the training data captures sufficiently the features you are trying to represent. click on Checking data in the Test FIS portion of the GUI. anfis from the Command Line As you can see.
The standard method for this type of prediction is to create a mapping 2110 .1x ( t ) 10 1 + x (t – τ) This time series is chaotic. τ = 17. say. x). and so there is no clearly defined period.2 Tutorial Using anfis for Chaotic Time Series Prediction The demo mgtsdemo uses anfis to predict a time series that is generated by the following MackeyGlass (MG) timedelay differential equation: 0.– 0. To obtain the time series value at integer points. The series will not converge or diverge. This is a benchmark problem in the neural network and fuzzy modeling research communities.2. and x(t) = 0 for t < 0. and the trajectory is highly sensitive to initial conditions. In timeseries prediction we want to use known values of the time series up to the point in time.dat t = mgdata(:. the result was saved in the file mgdata.2x ( t – τ ) · x ( t ) = . 1). x = mgdata(:. t+P. type load mgdata. plot(t. say. To plot the MG time series. 2). we applied the fourthorder RungeKutta method to find the numerical solution to the above MG equation. t. to predict the value at some point in the future. Here we assume x(0) = 1.dat.
default values are assumed. The generated FIS structure contains 16 fuzzy rules with 104 parameters. Following the conventional settings for predicting the MG time series. :). to a predicted future value x(t+P). We use the first 500 data values for the anfis training (these become the training data set). 2111 ..:)=[x(t18) x(t12) x(t6) x(t) x(t+6)]. x(t∆). the training input/output data will be a structure whose first component is the fourdimensional input w. while the others are used as checking data for validating the identified fuzzy model. (x(t(D1)∆). These defaults provide two generalized bell membership functions on each of the four inputs. Here is the code that generates this data: for t=118:1117. :). Since we did not specify numbers and types of membership functions used in the FIS.. There will be 1000 input/output data values. sampled every ∆ units in time.. and whose second component is the output s.anfis and the ANFIS Editor GUI from D sample data points. eight altogether. This is the task of genfis1: fismat = genfis1(trnData).. it is important to have the number of training data points be several times larger than the number parameters being estimated. chkData=Data(501:end. In order to achieve good generalization capability. end trnData=Data(1:500. the ratio between data and parameters is about five (500/104). the input training data for anfis is a four dimensional vector of the following form: w(t) = [x(t–18) x(t–12) x(t–6) x(t)] The output training data corresponds to the trajectory prediction: s(t) = x(t+6) For each t. In this case. Data(t117. For each t. we need an FIS structure that specifies the structure and initial parameters of the FIS for learning. This results in two 500point data structures: trnData and chkData. we set D = 4 and ∆ = P = 6. To start the training. x(t)). ranging in values from 118 to 1117.
.2 0 0.8 1 Input 4 1.fismat.4) plotmf(fismat.error1.4 0. 1) 'input'.8 1 Input 3 1.2 1 0.6 0.ss.chkData).6 0.2 0 0. type [fismat1.8 1 Input 2 1.4 0.1) plotmf(fismat. You can plot the input membership functions using the following commands.6 0.2 1 0. 1 0.4 0.2 0 0.2.6 0. subplot(2.fismat2. 2) 'input'.4 0.[].8 0.2. anfis(trnData. 3) 'input'. subplot(2. subplot(2.6 0. This takes about four minutes on a Sun SPARCstation 2 for 10 epochs of training. 4) These initial membership functions are shown below.8 0.6 0. 'input'.2) plotmf(fismat.6 0.2.2 1 0. the final FIS you choose would ordinarily be the one associated with the minimum checking 2112 .8 0.2 0 0.error2] = .2 To start the training.2.2 Tutorial The function genfis1 generates initial membership functions that are equally spaced and cover the whole input space.[]. Because the checking data option of anfis was invoked.6 0.8 1 Input 1 1.3) plotmf(fismat. subplot(2..8 0.
8 0.8 0. 2) 'input'.2) plotmf(fismat2.4 0.2 0 0.2 0 0.4 0. In addition to these error plots.8 0. chkData].2.8 1 Input 3 1.2. subplot(2.2 0 0. index = 125:1124.4 0. try anfis_output = evalfis([trnData.6 0.2 1 0. 1) 'input'. 4) Here is the result:.6 0.2 To plot the error signals type plot([error1.2 0 0.6 0. 2113 .6 0. you may want to plot the FIS output versus the training or checking data.6 0.2.4 0.8 0.8 1 Input 2 1. subplot(2. The following code will plot these new membership functions: subplot(2. respectively.8 1 Input 1 1.1) plotmf(fismat2.2. fismat2).4) plotmf(fismat2.anfis and the ANFIS Editor GUI error. 'input'. error2]). Here error1 and error2 are the root mean squared error for the training and checking data. subplot(2. 3) 'input'.6 0.2 1 0.6 0.3) plotmf(fismat2. 1 0. This is stored in fismat2.2 1 0.6 0. To compare the original MG time series and the fuzzy prediction side by side.8 1 Input 4 1.
Note that we have only trained for 10 epochs.fismat2. Better performance is expected if we apply more extensive training... All of the output arguments are also optional. dispOpt (display options).fismat. are optional.dispOpt. When the ANFIS Editor GUI is invoked using anfisedit.2 Tutorial subplot(211).In addition. and method (training method). MG Time Serise and ANFIS Prediction 1.6 200 x 10 5 0 −5 −10 200 300 400 500 600 700 800 900 1000 1100 −3 300 400 500 600 700 800 900 1000 1100 Prediction Errors Note that the difference between the original MG time series and the anfis estimated values is very small. More on anfis and the ANFIS Editor GUI The command anfis takes at least two and at most six input arguments. subplot(212). plot(t(index). only the training data set must exist prior to implementing anfis. the stepsize will be fixed when the adaptive neurofuzzy system is trained using this GUI tool. chkData (checking data).trnOpt. anfis(trnData.trnError. 2114 .ss.8 0. The prediction error is shown in the second plot with a much finer scale. In this section we discuss the arguments and range components of the command line function anfis.chkData. where trnOpt (training options). as well as the analogous functionality of the ANFIS Editor GUI.chkError] = . The general format is [fismat1. x(index) – anfis_output). This is why you can only see one curve in the first plot. plot(t(index). [x(index) anfis_output]).method).2 1 0.
As a result. the easier it will be for the model parameter training to converge. can be obtained either from any of the fuzzy editors: the FIS Editor. genfis1 (for which you only need to give numbers and types of membership functions). Human expertise about the target system to be modeled may aid in setting up these initial membership function parameters in the FIS structure. Each row starts with an input vector and is followed by an output value. trnData. and the Rule Editor from the ANFIS Editor GUI. (which specify the shapes of membership functions). since there is only one output. as well as to the ANFIS Editor GUI. Each row of trnData is a desired input/output pair of the target system to be modeled. the number of columns of trnData is equal to the number of inputs plus one. and causes an explosion of the number of rules when the number of inputs is moderately large. the more the initial membership functions resemble the optimal ones. the number of rows of trnData is equal to the number of training data pairs. this algorithm is selected with a radio button before the FIS is generated. and generates an FIS with the minimum number rules required to distinguish the fuzzy qualities associated with each of the clusters.anfis and the ANFIS Editor GUI Training Data The training data. and the parameters. throughout the learning process. the training error decreases.). the number of membership functions for each input. (which specifies such items as the number of rules in the FIS. Therefore. 2115 . This subtractive clustering method partitions the data into groups called clusters. at least locally. Note that genfis1 produces an FIS structure based on a fixed number of membership functions. The Fuzzy Logic Toolbox offers a method that will provide for some dimension reduction in the fuzzy inference system: you can generate an FIS structure using the clustering algorithm discussed in “Subtractive Clustering” on page 2123. etc. fismat. or from the command line function. (which allows an FIS structure to be loaded from the disk or the workspace). This invokes the socalled curse of dimensionality. more than four or five. Input FIS Structure The input FIS structure. and. is a required argument to anfis. and a hybrid method consisting of backpropagation for the parameters associated with the input membership functions. that is. and least squares estimation for the parameters associated with the output membership functions. Therefore. The FIS structure contains both the model structure. From the ANFIS Editor GUI. the Membership Function Editor. There are two methods that anfis learning employs for updating membership function parameters: backpropagation for all parameters (a steepest descent method).
However. • trnOpt(3): initial stepsize. Display Options Display options only apply to the command line function. the display options argument.2 Tutorial Training Options The ANFIS Editor GUI tool allows you to choose your desired error tolerance and number of training epochs. Usually we want the stepsize profile to be a curve that increases initially. then the default value is taken. whereas zero denotes don’t print this option.1. default = 1. • dispOpt(2): display error (each epoch).01. default = 1. whichever comes first. For the command line anfis. reaches some maximum. The default values are set up to cover a wide range of learning tasks.trnOpt(5)). For any specific application. • dispOpt(3): display stepsize (each epoch). default = 0. default= 0. and then decreases for the remainder of the training. there are no userspecified stepsize options for training the adaptive neuro fuzzy inference system generated using the ANFIS Editor GUI. • dispOpt(1): display ANFIS information. One is used to denote print this option. default = 10. • trnOpt(5): stepsize increase rate. If any element of trnOpt is an NaN or missing. dispOpt. default = 0. as we mentioned previously. This ideal stepsize profile is achieved by adjusting the initial stepsize and the increase and decrease rates (trnOpt(3) . • trnOpt(2): error tolerance. default = 1. before. • trnOpt(4): stepsize decrease rate.9. during. • dispOpt(4): display final results. default = 1. 2116 . default = 1. anfis. and after the training process. is a vector of either ones or zeros that specifies what information to display. you may want to modify these stepsize options in order to optimize the training. The training process stops if the designated epoch number is reached or the error goal is achieved. (print in the MATLAB command line window). Training option trnOpt for the command line anfis is a vector that specifies the stopping criteria and the stepsize adaptation strategy: • trnOpt(1): number of training epochs.
The training error trnError records the root mean squared error (RMSE) of the training data set at each epoch. If any element of dispOpt is NaN or missing. epochs curve as the system is trained. (the one associated with that training data output value). Training Error The training error is the difference between the training data output value.anfis and the ANFIS Editor GUI The default mode is displays all available information. These method choices are designated in the command line function. Method Both the ANFIS Editor GUI and the command line anfis apply either a backpropagation form of the steepest descent method for membership function parameter estimation. the default value will be taken. This is the FIS structure that you will use to represent the fuzzy system when there is no checking data used for model crossvalidation. Output FIS Structure for Training Data fismat1 is the output FIS structure corresponding to a minimal training error. the stepsize array ss records the stepsize during the training. Plotting ss gives the stepsize profile. The ANFIS Editor GUI will plot the training error vs. anfis. Using the command line anfis. This data also represents the FIS structure that is saved by the ANFIS Editor GUI when the checking data option is not used. Stepsize You cannot control the stepsize options with the ANFIS Editor GUI. and the output of the fuzzy inference system corresponding to the same training data input value. the output saved is that associated with the minimum checking error. When the checking data option is used. which serves as a reference for adjusting the initial stepsize and the corresponding decrease and increase 2117 . respectively. fismat1 is the snapshot of the FIS structure when the training error measure is at its minimum. or a combination of backpropagation and the leastsquares method to estimate membership function parameters. by 1 and 0. The choices for this argument are hybrid or backpropagation.
• If the error undergoes two consecutive combinations of one increase and one reduction. The default value for the initial stepsize is 0.01. 2118 . and its elements are generally distinct from those of the training data. and seeing how well the model responds to this data. or using the ANFIS Editor GUI. decrease the stepsize by multiplying it by a constant (ssdec) less than one. This data set is used to crossvalidate the fuzzy inference model. there is a tendency for the model to overfit the data on which is it trained. When the checking data option is used with anfis. A validation or checking data set can be useful for these situations.9. especially for a large number of training epochs. increase the stepsize by multiplying it by a constant (ssinc) greater than one. the model parameters that correspond to the minimum checking error are returned via the output argument fismat2. chkData. The FIS membership function parameters computed using the ANFIS Editor GUI when both training and checking data are loaded are associated with the training epoch that has a minimum checking error. respectively. The checking data is important for learning tasks for which the input number is large. The stepsize (ss) for the command line function anfis is updated according to the following guidelines: • If the error undergoes four consecutive reductions. If overfitting does occur. The checking data has the same format as that of the training data. especially if they are corrupted by noise. we cannot expect the fuzzy inference system to respond well to other independent data sets.1 and 0. In general we want a fuzzy inference system to track a given input/output data set well. This crossvalidation is accomplished by applying the checking data to the model. the default values for ssinc and ssdec are 1. Since the model structure used for anfis is fixed. and/or the data itself is noisy. When the command line anfis is invoked. the checking data is applied to the model at each training epoch.2 Tutorial rates. either via the command line. is used for testing the generalization capability of the fuzzy inference system at each epoch. All the default values can be changed via the training option for the command line anfis. Checking Data The checking data.
This is the FIS structure that should be used for further calculation if checking data is used for cross validation. As discussed in “ANFIS Editor GUI Example 2: Checking Data Doesn’t Validate Model” on page 2106. 2119 . depending on the behavior of the checking data error. fismat2. (the one associated with that checking data output value). Output FIS Structure for Checking Data The output of the command line anfis.anfis and the ANFIS Editor GUI The use of the minimum checking data error epoch to set the membership function parameters assumes • The checking data is similar enough to the training data that the checking data error will decrease as the training begins • The checking data increases at some point in the training. The ANFIS Editor GUI will plot the checking error vs. the resulting FIS may or may not be the one you should be using. The checking error chkError records the RMSE for the checking data at each epoch. is the output FIS structure with the minimum checking error. and the output of the fuzzy inference system corresponding to the same checking data input value. epochs curve as the system is trained. fismat2 is the snapshot of the FIS structure when the checking error is at its minimum. Checking Error The checking error is the difference between the checking data output value. after which data overfitting has occurred.
By iteratively updating the cluster centers and the membership grades for each data point. fcm iteratively moves the cluster centers to the “right” location within a data set. genfis2. fcm is a command line function whose output is a list of cluster centers and several membership grades for each data point. Fuzzy CMeans Clustering Fuzzy cmeans (FCM) is a data clustering technique wherein each data point belongs to a cluster to some degree that is specified by a membership grade. You can use the information returned by fcm to help you build a fuzzy inference system by creating membership functions to represent the fuzzy qualities of each cluster. This technique was originally introduced by Jim Bezdek in 1981 [Bez81] as an improvement on earlier clustering methods. The Fuzzy Logic Toolbox is equipped with some tools that allow you to find clusters in inputoutput training data. 2120 . The rules partition themselves according to the fuzzy qualities associated with each of the data clusters. The purpose of clustering is to identify natural groupings of data from a large data set to produce a concise representation of a system’s behavior. This type of FIS generation can be accomplished automatically using the command line function. It provides a method of how to group data points that populate some multidimensional space into a specific number of different clusters? The Fuzzy Logic Toolbox command line function fcm starts with an initial guess for the cluster centers.2 Tutorial Fuzzy Clustering Clustering of numerical data forms the basis of many classification and system modeling algorithms. The initial guess for these cluster centers is most likely incorrect. This iteration is based on minimizing an objective function that represents the distance from any given data point to a cluster center weighted by that data point’s membership grade. fcm assigns every data point a membership grade for each cluster. You can use the cluster information to generate a Sugenotype fuzzy inference system that best models the data behavior using a minimum number of rules. Additionally. which are intended to mark the mean location of each cluster.
8 1 Now we invoke the command line function.941176 Iteration count = 2. Load a data set and take a look at it.'o') 1 0.8 0. and ask it to find two clusters in this data set [center. fcm. and stepfcm. obj.2).1).2 0.4 0. obj. and objFcn contains a history of the objective function across the iterations.4 0.Fuzzy Clustering An Example: 2D Clusters Let’s use some quasirandom twodimensional data to illustrate how FCM clustering works. 0.7 0.3 .2 0.dat plot(fcmdata(:. distfcm. fcn = 8. load fcmdata.9 0.objFcn] = fcm(fcmdata.2). 2121 .5 0.6 0. The fcm function is an iteration loop built on top of several other routines. which initializes the problem. which steps through one iteration. The variable center contains the coordinates of the two cluster centers.6 0. U contains the membership grades for each of the data points. Iteration count = 1.277177 and so on until the objective function is no longer decreasing much at all. fcn = 7.1 0 0 0. namely initfcm. which is used for distance calculations.fcmdata(:.U.
'none'. hold on plot(center(1.center(2.'r').. maxU = max(U). plot(objFcn) objective function values 10 9 8 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11 Finally here is a plot displaying the two separate clusters as classified by the fcm routine.. 2). 'o'.1).'color'. 1).. 2).15.2 Tutorial Plotting the objective function shows the progress of the clustering. fcmdata(index1. 'linestyle'.2). index2 = find(U(2.'linestyle'.1).'LineWidth'.'kx'.15.center(1..1). line(fcmdata(index1.fcmdata(index2.'color'. obj_fcn] = fcm(fcmdata..'ko'. 'none'. line(fcmdata(index2.'marker'. :) == maxU).'g').'markersize'.2).dat [center.2) plot(center(2.2) 2122 . :) == maxU). index1 = find(U(1.'markersize'.'LineWidth'.2).'marker'. The following figure is generated using: load fcmdata. 'x'.. U.
number of dwelling units. [Chi94].3 0. The subclust function finds the clusters by using the subtractive clustering method. onepass method to take inputoutput training data and generate a Sugenotype fuzzy inference system that models the data behavior. Hence the model has five input variables and one output variable. Five demographic factors are considered: population.9 0. Subtractive clustering.4 0. is a fast. and total employment. The genfis2 function builds upon the subclust function to provide a fast.6 0. The cluster estimates obtained from the subclust function can be used to initialize iterative optimizationbased clustering methods (fcm) and model identification methods (like anfis). 1 0.7 0.8 1 Subtractive Clustering Suppose we don’t have a clear idea how many clusters there should be for a given set of data. median household income.2 0. onepass algorithm for estimating the number of clusters and the cluster centers in a set of data.6 0. An Example: Suburban Commuting In this example we apply the genfis2 function to model the relationship between the number of automobile trips generated from an area and the area’s demographics.8 0. vehicle ownership.4 0. Demographic and trip data are from 100 traffic analysis zones in New Castle County.2 0.5 0. 2123 .1 0 0 0.Fuzzy Clustering Cluster centers are indicated in the figure below by the large characters. Delaware.
the model type for the FIS structure is a first order Sugeno model with three rules. We can use evalfis to verify the model.fismat).2). we will use 75 data points as training data (datin and datout) and 25 data points as checking data. (resulting in fewer rules). plot(datin) subplot(2. Specifying a large cluster radius will usually yield a few large clusters in the data. The genfis2 function generates a model from data using clustering.1. (resulting in many rules). Here we call the genfis2 function using a cluster radius of 0. Of the original 100 data points. fismat=genfis2(datin. Specifying a small cluster radius will usually yield many small clusters in the data. and requires you to specify a cluster radius. (as well as for test data to validate the model). The cluster radius is specified as the third argument of genfis2. The checking data input/output pairs are denoted by chkdatin and chkdatout.0.2 Tutorial Load the data by typing tripdata subplot(2.5).1). plot(datout) 50 40 30 20 10 0 0 10 20 30 40 50 60 70 80 10 8 6 4 2 0 0 10 20 30 40 50 60 70 80 tripdata creates several variables in the workspace. trnRMSE=norm(fuzout–datout)/sqrt(length(fuzout)) 2124 . onepass method that does not perform any iterative optimization.5. The cluster radius indicates the range of influence of a cluster when you consider the data space as a unit hypercube. fuzout=evalfis(datin. An FIS structure is returned.1. genfis2 is a fast.datout.
The command line version of this is as follows: fismat2=anfis([datin datout]. we apply test data to the FIS. For this example.'o') hold off 9 8 7 6 5 4 3 2 1 0 0 5 10 15 20 25 At this point. we can use the optimization capability of anfis to improve the model.5276 The variable trnRMSE is the root mean square error of the system generated by the training data. chkfuzout=evalfis(chkdatin. To validate the generalizability of the model.6170 Not surprisingly. A plot of the testing data reveals the difference. we use the checking data for both checking and testing the FIS parameters.1]). we will try using a relatively short anfis training (50 epochs) without implementing the checking data option. we type: 2125 . chkRMSE=norm(chkfuzout–chkdatout)/sqrt(length(chkfuzout)) chkRMSE = 0.fismat).fismat. First. the model doesn’t do quite as good a job on the testing data.[50 0 0.Fuzzy Clustering trnRMSE = 0. After the training is done. but test the resulting FIS model against the test data. plot(chkdatout) hold on plot(chkfuzout.
but only a little with respect to the checking data. plot(chkdatout) hold on plot(chkfuzout2. 2126 .fismat2). chkRMSE2=norm(chkfuzout2–chkdatout)/sqrt(length(chkfuzout2)) chkRMSE2 = 0.5827 The model has improved a lot with respect to the training data.3407 chkfuzout2=evalfis(chkdatin.2 Tutorial fuzout2=evalfis(datin. fast method for generating a fuzzy model from data.fismat2). This reduces the problem of combinatorial explosion of rules when the input data has a high dimension (the dreaded curse of dimensionality). or as a preprocessor to anfis for determining the initial rules. including its checking data option.'o') hold off 9 8 7 6 5 4 3 2 1 0 0 5 10 15 20 25 Here we see that genfis2 can be used as a standalone. Overfitting Now let’s consider what happens if we carry out a longer (200 epoch) training of this system using anfis. An important advantage of using a clustering method to find rules is that the resultant rules are more tailored to the input data than they are in an FIS generated without clustering. trnRMSE2=norm(fuzout2–datout)/sqrt(length(fuzout2)) trnRMSE2 = 0. Here is a plot of the improved testing data.
Depending on the specified 2127 .. The error with the training data is the lowest we’ve seen.Fuzzy Clustering [fismat3.55 0. and the RMSE versus the checking data associated with each training epoch.5 Checking Error Training Error 0. after which it increases slightly..1]. This suggests that maybe we had gotten about as close as possible with this system already. the smallest value of the checking data error occurs at epoch 52.[200 0 0. Minimal training RMSE = 0. Maybe we have even gone so far as to overfit the system to the training data.35 0.45 0. though not by much. the RMSE versus the training data..fismat2.[]. anfis([datin datout].65 0.3 0 20 40 60 80 100 120 140 160 180 200 Epochs Here we can see that the training error settles at about the 50th epoch point.fismat4.582545 This looks good.stepSize. ANFIS training completed at epoch 200.6 0. and the error with the checking data is also lower than before. A look at the error history against both the training data and the checking data reveals much. Overfitting occurs when we fit the fuzzy system to the training data so well that it no longer does a very good job of fitting the checking data.. The long list of output arguments returns a history of the stepsizes. [chkdatin chkdatout]).trnErr. 0. even as anfis continues to minimize the error against the training data all the way to epoch 200.4 0. . The result is a loss of generality.326566 Minimal checking RMSE = 0. In fact.7 0.chkErr]= .
Once the data is loaded. clusterdemo. select them with the pulldown tabs. to load the data set. For example. More information on the options can be found in the entries for fcm on page 322. You can invoke findcluster with a data set directly.dat'). You use the pulldown tab under Method to change between fcm (fuzzy cmeans) and subtractiv (subtractive clustering). A Clustering GUI Tool There is also the Clustering GUI. this plot also indicates the model’s ability to generalize the test data. respectively. The clustering GUI looks like this. Load a data set (*. Choose fcm or subtractive clustering method. The data set must have the extension . Its use is fairly selfevident. type findcluster('clusterdemo.2 Tutorial error tolerance. Options change with method Start clustering the data. Choose two of your data variables to be plotted on the screen.dat) into your directory. and subclust on page 372. along with all of their options. which implements fcm and subclust. in order to open the GUI with a data set. Save the value of the cluster center.dat. 2128 .dat. findcluster. and is invoked using the command line function.
but only displays two of those dimensions. Use the pulldown tabs under Xaxis and Yaxis to select which data dimension you want to view. 2129 .Fuzzy Clustering The Clustering GUI works on multidimensional data sets.
The standalone Ccode fuzzy inference engine can read an FIS file and an input data file to perform fuzzy inference directly.fis > fis_out 2130 . We can prepare the input data file using MATLAB: [x.) Upon successful compilation. where each row of the matrix represents an input vector.fis. input_data = [x(:) y(:)].fis This generates 121 outputs on your screen.c.c –lm (Note that % is only symbolic of a UNIX prompt. –5:5).2 Tutorial StandAlone CCode Fuzzy Inference Engine In the fuzzy/fuzzy directory of the toolbox. You can direct the outputs to another file: % fismain fis_in mam21. and an FIS file that specifies the fuzzy inference system under consideration.c. which are provided as the source codes for a standalone fuzzy inference engine. type the executable command to see how it works: % fismain This prompts the following message: % Usage: fismain data_file fis_file This means that fismain needs two files to do its work: a data file containing rows of input vectors. and that you do not have to type fis. or it can be embedded in other external applications. y] = meshgrid(–5:5. mam21. fismain.c and fis. consider an FIS structure file named. save fis_in input_data –ascii This saves all the input data as a 121by2 matrix in the ASCII file fis_in. since it is included in fismain. To compile the standalone fuzzy inference engine on a UNIX system. type % cc –O –o fismain fismain. Now we can call the standalone code: % fismain fis_in mam21. For example. you can find two C files.c explicitly.
out.m. the compiled command fismain tries to find fismain. load fis_out max(max(matlab_out – fis_out)) ans = 4. so you are limited to the 11 membership functions that come with the toolbox.c and can be changed if necessary. • For the Macintosh. each row of the output matrix represents an output vector.in and fismain. fismat).fis as input data and FIS description files. In general. The syntax of fismain is similar to its MEXfile counterpart evalfis. IMP. and AGG functions. as long as __STDC__ is defined in ANSI compilers. 2131 .StandAlone CCode Fuzzy Inference Engine Now the file fis_out contains a 121by1 matrix.c. OR. The output is stored in fismain. except that all matrices are replaced with files. which contains all the necessary functions to perform the fuzzy inference process. type the following within MATLAB: fismat = readfis('mam21'). you need to change the file fis. respectively.c contains only the main() function and it is heavily documented for easy adaptation to other applications. • fismain. There are several things you should know about this standalone executable: • It is compatible with both ANSI and K & R standards for C code. matlab_out = evalfis(input_data.9583e–13 This tiny difference comes from the limited length printout in the file fis_out. To compare the results from the MATLAB MEXfile and the standalone executable. • Customized functions are not allowed in the standalone executable. These filenames are defined within Macintoshspecific #define symbols in fismain. • To add a new membership function or new reasoning mechanism into the standalone code. as well as other factory settings for AND.
the process of generating membership values for a fuzzy variable using membership functions.the process of transforming a fuzzy output of a fuzzy inference system into a crisp output. These are also known as logical connectives. antecedent .the overall name for a system that uses fuzzy reasoning to map an input space to an output space. The firing strength may be the result of an AND or an OR operation. consequent . fuzzy cmeans clustering .2 Tutorial Glossary This section is designed to briefly explain some of the specialized terms that are derived from fuzzy logic.the final (or “then”) part of a fuzzy rule.the combination of the consequents of each rule in a Mamdani fuzzy inference system in preparation for defuzzification.see firing strength. and NOT operators. Also known as a membership value or membership grade.a technique for automatically tuning Sugenotype inference systems based on training data.a data clustering technique wherein each data point belongs to a cluster to a degree specified by a membership grade. fuzzy singleton . this value is always limited to between 0 and 1. and it shapes the output function for the rule. defuzzification . firing strength . degree of membership . Adaptive NeuroFuzzy Inference System (ANFIS) . fuzzy inference system (FIS) .the output of a membership function.a set which can contain elements with only a partial degree of membership. OR.a fuzzy set with a membership function that is unity at a one particular point and zero everywhere else. 2132 .the degree to which the antecedent part of a fuzzy rule is satisfied. Also known as degree of fulfillment.the initial (or “if”) part of a fuzzy rule. aggregation . degree of fulfillment . fuzzification . fuzzy set . fuzzy operators .AND.
a type of fuzzy inference in which the consequent of each rule is a linear combination of the inputs. The output is a weighted linear combination of the consequents.(also known as Snorm) a twoinput function that describes a superset of fuzzy union (OR) operators. algebraic sum. and any of several parameterized Tconorms.a function that specifies the degree to which a given input belongs to a set or is related to a concept. 2133 .a type of fuzzy inference in which the fuzzy sets from the consequent of each rule are combined through the aggregation operator and the resulting fuzzy set is defuzzified to yield the output of the system. Sugenotype inference . In the Fuzzy Logic Toolbox it is only supported as part of a zeroorder Sugeno model. Mamdanitype inference .an output function that is given by a spike at a single number rather than a continuous curve. subtractive clustering . including maximum. membership function (MF) . Tnorm .a technique for automatically generating fuzzy inference systems by detecting clusters in inputoutput training data.Glossary implication . algebraic product. including minimum. Tconorm . and any of several parameterized Tnorms. singleton output function .a twoinput function that describes a superset of fuzzy intersection (AND) operators.the process of shaping the fuzzy set in the consequent based on the results of the antecedent in a Mamdanitype FIS.
1990. R. R. No. of the Ninth National Conf. and the NASA Joint Technology Workshop on Neural Networks and Fuzzy Logic.S. V. [Dub80] Dubois. J.” IEEE Transactions on Systems.. [Kau85] Kaufmann. and H. Assilian. the Industrial Fuzzy Control and Intelligent Systems Conference.” Proc. J.. Texas. and S. D. 762767.. “Fuzzy logic in control systems: fuzzy logic controllerparts 1 and 2. [Jan91] Jang. [Mam75] Mamdani. Introduction to Fuzzy Arithmetic. J.N. R. pp. of the International Joint Conference of the North American Fuzzy Information Processing Society Biannual Conference. Vol.” Proceedings of the IEEE. and C. pp. pp. 1997.. 113. and C. R. [Lee90] Lee. and M. Pattern Recognition with Fuzzy Objective Function Algorithms. 1985. “Neurofuzzy modeling and control.S.2 Tutorial References [Bez81] Bezdek. “Fuzzy Model Identification Based on Cluster Estimation. J. July 1991. 1. Sun.S. on Artificial Intelligence (AAAI91). J. Gulley. and Cybernetics. 1975. No. 3. 1994. 20. 1981. 7.. “An experiment in linguistic synthesis with a fuzzy logic controller.” Journal of Intelligent & Fuzzy Systems. Man.” Proc. Reinhold.” IEEE Transactions on Systems.M. Academic Press. 1994.T. pp 404435. 2134 . Vol.S.T. 1980. [Jan93] Jang. C. [Chi94] Chiu. Sun. “Fuzzy Modeling Using Generalized Neural Networks and Kalman Filter Algorithm. Vol. “Gain scheduling based fuzzy controller design. [Jan97] Jang. 2. New York. 665685. E. May 1993. Vol. S. Dec. Sept. Prentice Hall.S. San Antonio.C. NeuroFuzzy and Soft Computing: A Computational Approach to Learning and Machine Intelligence. No. “ANFIS: AdaptiveNetworkbased Fuzzy Inference Systems. March 1995. R. Man. A. Plenum Press.” International Journal of ManMachine Studies.H. [Jan95] Jang. and Cybernetics.C. New York. Fuzzy Sets and Systems: Theory and Applications. Gupta. Prade. [Jan94] Jang. J. 23. No. 2. and N. 3.
89102.H.” IEEE Transactions on Computers. E. [Yag80] Yager. R. “Knowledge representation in fuzzy logic. B.. 1. [Zad65] Zadeh. Saridis.” Information and Control. Man.References [Mam76] Mamdani. 9:4380 [Zad88] Zadeh. 2.. 8:301357. 1973. Gupta. [Sch63] Schweizer. “Fuzzy measures and fuzzy integrals: a survey. M. 1976. 3. 4. 1980. E.H. Stearns. Adaptive fuzzy systems and control: design and stability analysis.. “On a general class of fuzzy connectives. No.M. Parts 1. [Zad75] Zadeh. New York. L. Filev. “Fuzzy sets. pp. and D. “Generation of Fuzzy Rules by Mountain Clustering. 1989. 1985. M. L. L..” Information Sciences. “The concept of a linguistic variable and its application to approximate reasoning.. 4:235242.A. pp. Jan. pp. pp. [Sug85] Sugeno. “Outline of a new approach to the analysis of complex systems and decision processes. pp. Prentice Hall.. [Zad73] Zadeh. 8..A. 1965.” (M. pp. pp. 2. Industrial applications of fuzzy control. [Yag94] Yager. 1988.. 1975.” Computer.A. L. Vol. and 3. No.. [WidS85] Widrow. and D. R.A.” Fuzzy Sets and Systems. “Advances in the linguistic synthesis of fuzzy controllers. 1. 209219. and A.X. 89100. Vol. B. 1985. Vol. Prentice Hall. N. 8. Vol.R. Vol.. 2844. Gaines. 3. 1977. 338353. 8:199249. pp. L. [Wan94] Wang. 11821191. G. 1994. 1994. 669678. 26. No..” Publ. “Associative functions and abstract semigroups. [Mam77] Mamdani.” IEEE Transactions on Knowledge and Data Engineering. editors) Fuzzy Automata and Decision Processes. Co.” IEEE Transactions on Systems. Vol. Vol. NorthHolland.. [Zad89] Zadeh. and Cybernetics. [Sug77] Sugeno. 2135 . 10:6981.” Journal of Intelligent & Fuzzy Systems. Elsevier Science Pub. 1963. No. “Fuzzy Logic.A. L. and B. 1977. 1. Sklar. Adaptive Signal Processing.” International Journal of ManMachine Studies. 12. “Applications of fuzzy logic to approximate reasoning using linguistic synthesis. Math Debrecen. 8393.
2 Tutorial 2136 .
. . . . . . . . .3 Reference GUI Tools . . . . . . . . . . . . . . . Simulink Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Membership Functions . . . . . . . . . . . . . Demos . . . . . . . . . . . . . . . . . . . . 32 32 33 34 34 35 . . . . . . FIS Data Structure Management Advanced Techniques . . . . . . . . . . . . . . . . . .
Generalized bell curve membership function. The following tables contain the functions listed by topic. Rule Editor and parser. Rule Viewer and fuzzy inference diagram. Pishaped curve membership function. Basic FIS Editor. Membership Function Editor.3 Reference This section of the chapter contains brief descriptions of all the functions in the Fuzzy Logic Toolbox. 32 . Output Surface Viewer. GUI Tools Function anfisedit fuzzy mfedit ruleedit ruleview surfview Purpose ANFIS Editor GUI. Gaussian curve membership function. Membership Functions Function dsigmf gauss2mf gaussmf gbellmf pimf Purpose Difference of two sigmoid membership functions. Twosided Gaussian curve membership function.
Generic membership function evaluation. Zshaped curve membership function. Parse fuzzy rules.Function psigmf smf sigmf trapmf trimf zmf Purpose Product of two sigmoidal membership functions. Get fuzzy system properties. FIS Data Structure Management Function addmf addrule addvar defuzz evalfis evalmf gensurf getfis mf2mf newfis parsrule plotfis plotmf Purpose Add membership function to FIS. Triangular membership function. Add rule to FIS. Trapezoidal membership function. Create new FIS. Sshaped curve membership function. Add variable to FIS. Translate parameters between functions. Perform fuzzy inference calculation. Plot all of the membership functions associated with a given variable. Defuzzify membership function. 33 . Sigmoid curve membership function. Generate FIS output surface. Display FIS inputoutput structure.
3
Reference
Function readfis rmmf rmvar setfis showfis showrule writefis
Purpose
Load FIS from disk. Remove membership function from FIS. Remove variable from FIS. Set fuzzy system properties. Display annotated FIS. Display FIS rules. Save FIS to disk.
Advanced Techniques
Function anfis fcm genfis1 genfis2 subclust Purpose
Training routine for a Sugenotype FIS (MEX only). Find clusters with FCM clustering. Generate FIS matrix using grid method. Generate FIS matrix using subtractive clustering. Find cluster centers with subtractive clustering.
Simulink Blocks
Function fuzblock sffis Purpose
Fuzzy logic controller blocks and demo blocks. Fuzzy inference Sfunction.
34
Demos
Function defuzzdm fcmdemo fuzdemos gasdemo juggler invkine irisfcm noisedm slbb slcp sltank sltankrule sltbu Purpose
Defuzzification methods. FCM clustering demo (2D). GUI for Fuzzy Logic Toolbox demos. ANFIS demo for fuel efficiency using subclustering. Balljuggler with Rule Viewer. Inverse kinematics of a robot arm. FCM clustering demo (4D). Adaptive noise cancellation. Ball and beam control (Simulink ). Inverted pendulum control (Simulink ). Water level control (Simulink). Water level control with Rule Viewer (Simulink). Truck backerupper (Simulink only).
35
addmf
Purpose Synopsis Description
3addmf
Add a membership function to an FIS.
a = addmf(a,'varType',varIndex,'mfName','mfType',mfParams)
A membership function can only be added to a variable in an existing MATLAB workspace FIS. Indices are assigned to membership functions in the order in which they are added, so the first membership function added to a variable will always be known as membership function number one for that variable. You cannot add a membership function to input variable number two of a system if only one input has been defined. The function requires six input arguments in this order:
1 A MATLAB variable name of a FIS structure in the workspace 2 A string representing the type of variable you want to add the membership
function to ('input' or 'output')
3 The index of the variable you want to add the membership function to 4 A string representing the name of the new membership function 5 A string representing the type of the new membership function 6 The vector of parameters that specify the membership function
36
addmf
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)
poor
1
good
excellent
Degree of belief
0.8
0.6
0.4
0.2
0 0 1 2 3 4 5 6 7 8 9 10
service
See Also
addrule, addvar, plotmf, rmmf, rmvar
37
addrule
Purpose Synopsis Description
3addrule
Add a rule to an FIS.
a = addrule(a,ruleList) addrule has two arguments. The first argument is the MATLAB workspace variable FIS name. The second argument for addrule is a matrix of one or more
rows, each of which represents a given rule. The format that the rule list matrix must take is very specific. If there are m inputs to a system and n outputs, there must be exactly m + n + 2 columns to the rule list. The first m columns refer to the inputs of the system. Each column contains a number that refers to the index of the membership function for that variable. The next n columns refer to the outputs of the system. Each column contains a number that refers to the index of the membership function for that variable. The m + n + 1 column contains the weight that is to be applied to the rule. The weight must be a number between zero and one, and is generally left as one. The m + n + 2 column contains a 1 if the fuzzy operator for the rule’s antecedent is AND. It contains a 2 if the fuzzy operator is OR.
Example
ruleList=[ 1 1 1 1 1 1 2 2 1 1]; a = addrule(a,ruleList);
If the above system a has two inputs and one output, the first rule can be interpreted as: “If input 1 is MF 1 and input 2 is MF 1, then output 1 is MF 1.”
See Also
addmf, addvar, rmmf, rmvar, parsrule, showrule
38
addvar
Purpose Synopsis Description
3addvar
Add a variable to an FIS.
a = addvar(a,'varType','varName',varBounds) addvar has four arguments in this order:
1 The name of a FIS structure in the MATLAB workspace 2 A string representing the type of the variable you want to add ('input' or
'output')
3 A string representing the name of the variable you want to add 4 The vector describing the limiting range values for the variable you want to
add Indices are applied to variables in the order in which they are added, so the first input variable added to a system will always be known as input variable number one for that system. Input and output variables are numbered 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
39
anfis
Purpose Synopsis
3anfis
Training routine for Sugenotype FIS (MEX only).
[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 the major training routine for Sugenotype fuzzy inference systems. anfis uses a hybrid learning algorithm to identify parameters of Sugenotype fuzzy inference systems. It applies a combination of the leastsquares method and the backpropagation gradient descent method for training FIS membership function parameters to emulate a given training data set. anfis can also be invoked using an optional argument for model validation. The type of model validation that takes place with this option is a checking for model overfitting, and the argument is a data set called the checking data set. The arguments in the above description for anfis are as follows: • trnData: the name of a training data set. This is a matrix with all but the last column containing input data, while the last column contains a single vector of output data. • fismat: the name of an FIS, (fuzzy inference system) used to provide anfis with an initial set of membership functions for training. Without this option, anfis will use genfis1 to implement a default initial FIS for training. This default FIS will have two membership functions of the Gaussian type, when invoked with only one argument. If fismat is provided as a single number (or a vector), it is taken as the number of membership functions (or the vector whose entries are the respective numbers of membership functions associated with each respective input when these numbers differ for each input). In this case, both arguments of anfis are passed to genfis1 to generate a valid FIS structure before starting the training process.
310
When any training option is entered as NaN the default options will be in force. the default options will be in force.anfis • trnOpt: vector of training options. • optMethod: optional optimization method used in membership function parameter training: either 1 for the hybrid method or 0 for the backpropagation method. When any display option is entered as NaN. which is a combination of least squares estimation with backpropagation. A 0 means the corresponding information is not displayed on the screen. 311 .1) • dispOpt: vector of display options that specify what message to display in the MATLAB command window during training. The default value for any display option is 1. The default method is invoked whenever the entry for this argument is anything but 0. These options are as follows: dispOpt(1): ANFIS information. The default method is the hybrid method.9) trnOpt(5): step size increase rate (default: 1. These options are as follows: trnOpt(1): training epoch number (default: 10) trnOpt(2): training error goal (default: 0) trnOpt(3): initial step size (default: 0. which means the corresponding information is displayed. The training process stops whenever the designated epoch number is reached or the training error goal is achieved. This data set is a matrix in the same format as the training data set. such as numbers of input and output membership functions. and so on (default: 1) dispOpt(2): error (default: 1) dispOpt(3): step size at each parameter update (default: 1) dispOpt(4): final results (default: 1) • chkData: the name of an optional checking data set for overfitting model validation.01) trnOpt(4): step size decrease rate (default: 0.
respectively. The step size is increased (by multiplying it with the increase rate) if the error measure undergoes four consecutive decreases. • fismat2 is the FIS structure whose parameters are set according to a minimum checking error criterion.m. but do want to specify succeeding arguments. Either NaNs or empty matrices must be used as placeholders for variables if you don’t want to specify them. The range variables in the above description for anfis are as follows: • fismat1 is the FIS structure whose parameters are set according to a minimum training error criterion. Default values can be changed directly by modifying the file anfis. when you implement the checking data option of anfis.anfis Note on anfis arguments: When anfis is invoked with two or more arguments. • stepsize is an array of step sizes. for example. 312 . • error1 or error2 is an array of root mean squared errors representing the training data error signal and the checking data error signal. any optional arguments will take on their default values if they are entered as NaNs or empty matrices. The step size is decreased (by multiplying it with the component of the training option corresponding to the step size decrease rate) if the error measure undergoes two consecutive combinations of an increase followed by a decrease.
evalfis(x. pp.x. R.numMFs. numMFs = 5. Vol. Man.. pp. on Artificial Intelligence (AAAI91). 23. 762767.20).in_fismat.” IEEE Transactions on Systems. y = sin(2*x). 3. R.out_fismat)).mfType).'ANFIS Output').S. 313 . J. of the Ninth National Conf. plot(x. “Fuzzy Modeling Using Generalized Neural Networks and Kalman Filter Algorithm.1:10)'. and Cybernetics. Jang. anfis See Also References Jang./exp(x/5).y. legend('Training Data'.” Proc.. trnData = [x y]. No. genfis1. mfType = 'gbellmf'. out_fismat = anfis(trnData. May 1993. in_fismat = genfis1(trnData. J.anfis Example x = (0:0. “ANFIS: AdaptiveNetworkbased Fuzzy Inference Systems. 665685. epoch_n = 20.S. July 1991.
Data appears in the plot region. Load FIS or generate FIS from loaded data using your chosen number of MFs and rules or fuzzy. and number of epochs. or checking data from disk or workspace. Clear Data unloads a loaded data set checked under Type:. input membership functions and output membership functions Testing Data appears on the plot in blue as . Training Data appears on the plot in blue as o o o Checking Data appears on the plot in blue as +++ FIS Output appears on the screen in red as *** After you generate or load a FIS. error tolerance. The plot region is cleared even if other data types are still loaded.anfisedit Purpose Synopsis 3anfisedit To open the ANFIS Editor GUI. Using anfisedit. This generates error plots in the plot region. Test data against the FIS model. this button allows you to open a graphical representation of its input/output structure. or load demo data. Train FIS after setting optimization method.. The plot appears in the plot region. you bring up the ANFIS Editor GUI from which you can load a data set and train anfis. Undo Open FIS or Edit with any of the other GUIs. testing.. anfisedit('a') anfisedit(a) anfisedit Description Load or save fuzzy Sugeno system or open new Sugeno system. Plot region Status of the number of inputs. The ANFIS Editor GUI invoked using 314 . Load either training. outputs.
The File menu is the same as the one found on the FIS Editor. there is a menu bar that allows you to open related GUI tools.fis. Edit rules.. View surface. Refer to fuzzy on page 329 for more information.. to invoke the Rule Viewer. mfedit. and so on. to invoke the Membership Function Editor. Menu Items On the ANFIS Editor GUI. stored as a variable in the MATLAB workspace. Edit membership functions.. anfisedit(a) operates the same way for a FIS structure a. a. • Use the following Edit menu item: Undo to undo the most recent change.. to invoke the FIS Editor. See Also fuzzy. brings up the ANFIS Editor GUI from which you can implement anfis using a FIS structure stored as a file on your disk called. to invoke the Surface Viewer....anfisedit anfisedit('a')... • Use the following View menu items: Edit FIS properties. to invoke the Rule Editor. ruleview. ruleedit. surfview 315 . open and save systems. Refer to “anfis and the ANFIS Editor GUI” on page 292 for more information about how to use anfisedit.. View rules.
0 FIS matrix to a version 2.convertfis Purpose Synopsis Description 3convertfis Convert a Fuzzy Logic Toolbox version 1. 316 .0 FIS structure.0 structure. fis_new=convertfis(fis_old) convertfis takes a version 1.0 FIS matrix and converts it to a version 2.
mf = trapmf(x.1:10.mf.type) defuzz(x. type. xx = defuzz(x.mf.type) returns a defuzzified value out. it is assumed to be a userdefined function. out = defuzz(x. 317 .mf. The variable type can be one of the following. of a membership function mf positioned at associated variable value x. • centroid: centroid of area method • bisector: bisector of area method • mom: mean of maximum method • som: smallest of maximum method • lom: largest of maximum method If type is not one of the above. x and mf are passed to this function to generate the defuzzified output. Examples x = −10:0.[−10 −8 −4 7]). according to the argument. using one of several defuzzification strategies.'centroid').defuzz Purpose Synopsis Description 3defuzz Defuzzify membership function.
smf.y) xlabel('dsigmf. and is the difference between two of these sigmoidal functions: f1(x. evalmf.dsigmf Purpose Synopsis Description 3dsigmf Builtin membership function composed of the difference between two sigmoidal membership functions. and c2. a1. a2. Example x=0:0. psigmf. P=[5 2 5 7]') 1 0.25 0 0 2 4 6 dsigmf. mf2mf.5 0.a.1:10.f2(x. pimf.[5 2 5 7]). c2) The parameters are listed in the order: [a1 c1 a2 c2]. P = [5 2 5 7] 8 10 See Also gaussmf. trimf. zmf 318 . a2. gbellmf.75 0. trapmf. c1. c ) = ) –a ( x – c 1+e The membership function dsigmf depends on four parameters.[a1 c1 a2 c2]) The sigmoidal membership function used here depends on the two parameters a and c and is given by 1 f ( x . y=dsigmf(x. c1) . plot(x. sigmf. y = dsigmf(x. gauss2mf. a1.
IRR. IRR.fismat) output= evalfis(input. • fismat: an FIS structure to be evaluated. ARR]= evalfis(input.fismat. and L is the number of output variables for the FIS. If input is an MbyN matrix. • ARR: the numPtsbyL matrix of the aggregate values sampled at numPts along the output range for each output. then evalfis takes each row of input as an input vector and returns the MbyL matrix to the variable. (only one set of inputs is applied). ARR]= evalfis(input. These optional range variables are: • IRR: the result of evaluating the input values through the membership functions. • numPts: an optional argument that represents the number of sample points on which to evaluate the membership functions over the input or output range. where each row is an output vector and L is the number of output variables. numPts) evalfis has the following arguments: Description • input: a number or a matrix specifying input values. the next numRules columns of this matrix correspond to the second output. where numRules is the number of rules. output= evalfis(input. The range labels for evalfis are as follows: • output: the output matrix of size MbyL. and so forth.evalfis Purpose Synopsis 3evalfis Perform fuzzy inference calculations. numPts) [output. • ORR: the result of evaluating the output values through the membership functions. This is a matrix of size numPtsbynumRules*L. The optional range variables for evalfis are only calculated when the input argument is a row vector.fismat.fismat) [output. and L is the number of outputs. ORR. This is a matrix of size numRulesbyN. where numRules is the number of rules. The first numRules columns of this matrix correspond to the first output. where N is number of input variables. output. If this argument is not used. 319 . the default value of 101 point is used. and N is the number of input variables. where M represents the number of input values specified above. ORR.
this function computes the output vector. of the fuzzy inference system specified by the structure. input.evalfis When invoked with only one range variable. out = evalfis([2 1. gensurf 320 . Example fismat = readfis('tipper'). fismat. 4 9]. for the input value specified by the number or matrix.fismat) This generates the response out = 7.0169 19.6810 See Also ruleview. output.
gaussmf. mftype = 'gbellmf'. mfType is a membership function from the toolbox.1:10. psigmf. y = evalmf(x. pimf. mf2mf. because it evaluates any membership function whose name it doesn’t recognize.25 0 0 2 4 6 gbellmf.evalmf Purpose Synopsis Description 3evalmf Generic membership function evaluation. smf. where x is the variable range for the membership function evaluation. evalmf will still work. If you want to create your own custom membership function. and mfParams are appropriate parameters for that function. mfparams = [2 4 6]. P=[2 4 6]') 1 0.mfParams. Examples x=0:0. gauss2mf. P = [2 4 6] 8 10 See Also dsigmf.mftype). trimf.y) xlabel('gbellmf.mfparams. y=evalmf(x. gbellmf. plot(x. sigmf.5 0. zmf 321 .75 0. trapmf.mfType) evalmf evaluates any membership function.
the default value for that option is used instead. introduce a stopping criteria. and/ or set the iteration information display: options(1): exponent for the partition matrix U (default: 2. each row is a sample data point • cluster_n: number of clusters (greater than one) The output arguments of this function are: • center: matrix of final cluster centers where each row provides the center coordinates • U: final fuzzy partition matrix (or membership function matrix) • obj_fcn: values of the objective function during iterations fcm(data.U.fcm Purpose Synopsis Description 3fcm Fuzzy cmeans clustering.0) options(2): maximum number of iterations (default: 100) options(3): minimum amount of improvement (default: 1e5) options(4): info display during iteration (default: 1) If any entry of options is NaN. U.obj_fcn] = fcm(data. The clustering process stops when the maximum number of iterations is reached. to control clustering parameters. 322 . obj_fcn] = fcm(data. cluster_n) applies the fuzzy cmeans clustering method to a given data set.options) uses an additional argument variable.cluster_n) [center. The input arguments of this function are: • data: data set to be clustered. or when the objective function improvement between two consecutive iterations is less than the minimum amount of improvement specified. options. [center.cluster_n.
'o'). index2 = find(U(2. 'r'). 'color'.obj_fcn] = fcm(data.1). line(data(index1. '*'. data(index2.1). 'linestyle'. line(data(index2. 'color'.:) == maxU). 'none'. 2). data(index1. plot(data(:. 323 .U. 2).2). 'none'.1). maxU = max(U). 2). 'marker'. 'linestyle'. [center. data(:. 'g').fcm Example data = rand(100. 2). index1 = find(U(1. :) == maxU). 'marker'. '*'.
plotting up to the first two dimensions of the data only. For example. in the order in which the data appears in the data set. A description of the options for fuzzy subclustering is found in subclust on page 372. and Save Center will save the cluster center. When operating on a data set. Use the pulldown tabs under Xaxis and Yaxis to select which data dimension you want to view. findcluster findcluster('file. 324 . The options for each of these methods are set to default values.dat') findcluster brings up a GUI to implement fuzzy cmeans (fcm) and/or fuzzy subtractive clustering (subtractiv) using the pulldown tab under Method on the GUI. file. data_2. but only displays two of those dimensions. This tool works on multidimensional data sets. this tool labels the data as data_1. data_4. data_5. Data is entered using the Load Data button.dat) loads the data set automatically. These can be changed. findcluster (file.dat.findcluster Purpose Synopsis Description 3findcluster Interactive clustering GUI for fuzzy cmeans and subclustering. Start will perform the clustering. if you have data that is fivedimensional. A description of the options for fuzzy cmeans is found in fcm on page 322. data_3.
dat') fcm.findcluster You can still choose which two dimensions of the data you want to cluster after the GUI comes up. subclust 325 . Example See Also findcluster('clusterdemo.
max_x] x = linspace(min_x. max_x.1. A. B. A. operator) returns a fuzzy set C as the result of applying the function represented by the string. A. 'b'. title('fuzzy subtraction AB'). 'b'. 'm:'.2). x.% this determines MF's resolution min_x = 20. A. title('fuzzy addition A+B'). C2 = fuzarith(x. C2. that performs a binary operation on the sampled convex fuzzy sets A and B. but this will not affect the correctness of this function. Remark Example Fuzzy addition might generate the message: divide by zero. and 'div'. B. x. subplot(2. and X are vectors of the same dimension. 'c'). • A. operator.1). x. subplot(2. 'prod'). • The returned fuzzy set C is a column vector with the same length as X. B. B.% universe is [min_x. A = trapmf(x. 326 . C = fuzarith(X. 'c'). x. C = fuzarith(X. C1.% trapezoidal fuzzy set A B = gaussmf(x. B. max_x = 20. C3 = fuzarith(x. 'm:'. 'sub'. • operator is one of the following strings: 'sum'. [10 2 1 3]). A. [2 5]). The elements of A and B are derived from convex functions of the sampled universe.fuzarith Purpose Synopsis Description 3fuzarith To perform fuzzy arithmetic. 'sum'). B. B.1. point_n = 101. X. A.% Gaussian fuzzy set B C1 = fuzarith(x. 'sub'). plot(x. A. 'prod'. point_n)'. plot(x. operator) Using interval arithmetic. B.
and a Simulink diagram with a Fuzzy Logic Controller block opens. To open this dialog box for the Fuzzy Logic Controller With Rule Viewer block. these signals will be passed out of the block on one multiplexed line. (see also ruleview on page 361). This box contains the name of the FIS structure in the workspace that corresponds to the desired fuzzy system you want in your Simulink model. you have to 1 Doubleclick on this block. If the fuzzy inference system has multiple inputs. if the system has multiple outputs. contains two Simulink blocks you can use: • The Fuzzy Logic Controller • The Fuzzy Logic Controller With Rule Viewer. The dialog box associated with either of these blocks is found by doubleclicking on the Fuzzy Logic Controller block. these inputs should be multiplexed together before feeding them into either the Fuzzy Logic Controller or the Fuzzy Logic Controller With Rule Viewer block. ruleview 327 . See Also sffis. Similarly. 2 Doubleclick on the second Fuzzy Logic Controller block that pops open. fuzblock This command brings up a Simulink system that.fuzblock Purpose Synopsis Description 3fuzblock Simulink fuzzy logic controller block. This block forces the Rule Viewer to pop open during a Simulink simulation. in addition to some Simulink demo blocks.
328 .fuzdemos Purpose Synopsis Description 3fuzdemos List of all Fuzzy Logic Toolbox demos. fuzdemos This function brings up a GUI that allows you to choose between any of several Fuzzy Logic Toolbox demos listed under “Demos” on page 35.
fuzzy fuzzy(fismat) This GUI tool allows you to edit the highest level features of the fuzzy inference system. for more information about how to use the GUIs associated with fuzzy. The Diagram The diagram displayed at the top of the window shows the inputs. and so on. Doubleclick on the fuzzy rule processor to bring up the Rule Editor.. and a central fuzzy rule processor. It allows you to call the various other editors to operate on the FIS. Click on one of the variable boxes to make the selected box the current variable. such as the number of input and output variables. If 329 . the defuzzification method used.fuzzy Purpose Synopsis 3fuzzy To invoke the basic FIS editor. Doubleclick on one of the variables to bring up the Membership Function Editor. The FIS Editor is the highlevel display for any fuzzy logic inference system. You should see the box highlighted in red. This interface allows convenient access to all other editors with an emphasis on maximum flexibility for interaction with the fuzzy system. outputs. Refer to “The FIS Editor” on page 249 and ff.
. it is connected to the rule processor block with a dashed rather than a solid line.. • Under View select: Edit MFs.. to save the system to the currently named FIS structure variable in the workspace... to invoke the ANFIS Editor for single output Sugeno systems only. • Under File select: New Mamdani FIS. Save to disk to save the current system to a . to invoke the Surface Viewer. Save to workspace. to open a new Mamdanistyle system with no variables and no rules called Untitled. Edit rules.. Open from disk. Close window to close the GUI. 330 . Remove variable to delete a selected variable. open and save systems. Undo to undo the most recent change.. to invoke the Rule Editor.. New Sugeno FIS. Open from workspace. View surface. to open a new Sugenostyle system with no variables and no rules called Untitled. Edit anfis.. to load a system from a specified FIS structure variable in the workspace. Save to disk as..fuzzy a variable exists but is not mentioned in the rule base. to load a system from a specified . Save to workspace as..... to invoke the Membership Function Editor. to save the system to a specified FIS structure variable in the workspace. to save the current system to disk with the option to rename or relocate the file. • Under Edit select: Add input to add another input to the current system.. Menu Items The FIS Editor displays a menu bar that allows you to open related GUI tools. to invoke the Rule Viewer.fis file on disk.... Add output to add another output to the current system.... View rules. and so on..fis file on disk...
for a custom operation. This selection is not available for Sugenostyle fuzzy inference. or Custom. som (smallest of maximum). • Implication method: Choose min. choose centroid. probor (probabilistic or). for a custom operation. For Sugenostyle inference. mom (middle of maximum). • Defuzzification method: For Mamdanistyle inference. for a custom operation. or Custom. • Or method: Choose max. surfview. for a custom operation. prod. ruleview. This selection is not available for Sugenostyle fuzzy inference. choose between wtaver (weighted average) or wtsum (weighted sum). prod.fuzzy Inference Method Popup Menus Five popup menus are provided to change the functionality of the five basic steps in the fuzzy implication process: • And method: Choose min. sum. ruleedit. anfisedit 331 . bisector. lom (largest of maximum). or Custom. • Aggregation method: Choose max. or Custom. or Custom. for a custom operation. See Also mfedit. probor.
σ. c1. the gauss2mf function reaches a maximum value of 1. c2]. The parameters are listed in the order: [sig1. 332 . the maximum value is less than one. Otherwise. sig2.gauss2mf Purpose Synopsis Description 3gauss2mf Gaussian combination membership function. The second function specified by sig2 and c2 determines the shape of the rightmost curve. specified by sig1 and c1. y = gauss2mf(x.[sig1 c1 sig2 c2]) The Gaussian function depends on two parameters sig and c as given by –( x – c ) 2 2σ 2 f ( x . The first function. c ) = e The function gauss2mf is a combination of two of these. Whenever c1 < c2. determines the shape of the leftmost curve.
gauss2mf. [2 7 1 5]). See Also dsigmf. plot(x. zmf 333 . smf. y3 = gauss2mf(x. 'off'). pimf. mf2mf. [2 8 1 4]). [2 6 1 6]). y2 = gauss2mf(x. gbellmf.gauss2mf Examples x = (0:0. y5 = gauss2mf(x. y4 = gauss2mf(x. psigmf.1:10)'. y1 = gauss2mf(x. [y1 y2 y3 y4 y5]). evalmf. [2 4 1 8]). 'numbertitle'. 'gauss2mf'. sigmf. trimf. trapmf. set(gcf. 'name'. [2 5 1 7]).
gaussmf. y = gaussmf(x.σ. y=gaussmf(x. evalmf. zmf 334 . psigmf.gaussmf Purpose Synopsis Description 3gaussmf Gaussian curve builtin membership function. gbellmf.75 0. mf2mf. sigmf. trapmf. P=[2 5]') 1 0.1:10.[sig c]) The symmetric Gaussian function depends on two parameters σ and c as given by f ( x .25 0 0 2 4 6 gaussmf. trimf. plot(x.5 0. c ) = e –( x – c ) 2 2σ 2 The parameters for gaussmf represent the parameters σ and c listed in order in the vector [sig c]. smf. P = [2 5] 8 10 See Also dsigmf.[2 5]). pimf.y) xlabel('gaussmf. Example x=0:0.
25 0 0 2 4 6 gbellmf. gauss2mf. c ) = x – c 2b 1 + a where the parameter b is usually positive. b. plot(x. Example x=0:0. trimf. b. as the vector whose entries are a.a.gbellmf Purpose Synopsis Description 3gbellmf Generalized bellshaped builtin membership function. respectively.[2 4 6]). b.1:10. psigmf. y = gbellmf(x. y=gbellmf(x. zmf 335 . trapmf. pimf. sigmf. P = [2 4 6] 8 10 See Also dsigmf.params) The generalized bell function depends on three parameters a. mf2mf. The parameter c locates the center of the curve. Enter the parameter vector params. evalmf. and c as given by 1 f ( x . smf. gaussmf. and c.75 0.y) xlabel('gbellmf. the second argument for gbellmf.5 0. P=[2 4 6]') 1 0.
numMFs. is 2. • outmftype is a string that specifies the membership function type associated with the output. • inmftype is a string array in which each row specifies the membership function type associated with each input. The output membership function type must be either linear or constant. fismat = genfis1(data) fismat = genfis1(data. inmftype. Again. The number of membership functions associated with the output is the same as the number of rules generated by genfis1. data. The arguments for genfis1 are as follows: • data is the training data matrix. There can only be one output. and the last column representing the single output. the default input or output membership function type is 'gbellmf'. outmftype) genfis1 generates a Sugenotype FIS structure used as initial conditions (initialization of the membership function parameters) for anfis training. 336 . These are used whenever genfis1 is invoked without the last three arguments. outmftype) generates a FIS structure from a training data set. genfis1(data. then it suffices to make numMFs a single number.inmftype. since this is a Sugenotype system. which must be entered with all but the last columns representing input data. If you want the same number of membership functions to be associated with each input. this can be a onedimensional single string if the type of membership functions associated with each input is the same. The default number of membership functions. using a grid partition on the data (no clustering).numMFs.genfis1 Purpose Synopsis Description 3genfis1 Generate an FIS structure from data without data clustering. • numMFs is a vector whose coordinates specify the number of membership functions associated with each input. numMFs.
1 0. numMFs = [3 7].mf] = plotmf(fismat.9 1 1 0.6 0. plot(x.4 0. [x.1)5 rand(10.8 0.mf).1) 10*rand(10.1).4 0. xlabel('input 1 (pimf)'). [x.'trimf').'input'.1). fismat = genfis1(data.1.'input'.2).3 0.1 0.genfis1 Example data = [rand(10. mfType = str2mat('pimf'.mf).4 0.mfType).2 0.8 0.2 0 −5 −4 −3 −2 −1 0 1 input 2 (trimf) 2 3 4 5 See Also anfis 337 . subplot(2. plot(x.8 0.2 0 0 0.6 0.mf] = plotmf(fismat. xlabel('input 2 (trimf)').1)].6 input 1 (pimf ) 0.1. subplot(2.numMFs.2).7 0.5 0.
The arguments for genfis2 are as follows: • Xin is a matrix in which each row contains the input values of a data point. if the data dimension is 3 (e.e. For example. xBounds = [10 0 1. then the scalar value is applied to all data dimensions.genfis2 Purpose Synopsis 3genfis2 Generate an FIS structure from data using subtractive clustering.radii) fismat = genfis2(Xin. and 0. Xin has two columns and Xout has one column). This function returns an FIS structure that contains a set of fuzzy rules to cover the feature space.options) Description Given separate sets of input and output data. and data values in the third data 338 .5. The first row of xBounds contains the minimum axis range values and the second row contains the maximum axis range values for scaling the data in each dimension. 0. the first column of Xin. • xBounds is a 2byN optional matrix that specifies how to map the data in Xin and Xout into a unit hyperbox.3 times the width of the data space.3] specifies that the ranges of influence in the first. genfis2 generates an FIS using fuzzy subtractive clustering.5 0.Xout. 10 50 1] specifies that data values in the first data dimension are to be scaled from the range [10 +10] into values in the range [0 1]. second. • Xout is a matrix in which each row contains the output values of a data point...radii.Xout. radii = [0.xBounds. assuming the data falls within a unit hyperbox. respectively. If radii is a scalar. and the column of Xout) are 0. i.radii. and third data dimensions (i.4.. each cluster center will have a spherical neighborhood of influence with the given radius. When there is only one output. the second column of Xin.xBounds) fismat = genfis2(Xin. genfis2 may be used to generate an initial FIS for anfis training by first implementing subtractive clustering on the data. For example.4 0.Xout. where N is the data (row) dimension. data values in the second data dimension are to be scaled from the range [0 50]. The rule extraction method first uses the subclust function to determine the number of rules and antecedent membership functions and then uses linear least squares estimation to determine each rule’s consequent equations.e.g. fismat = genfis2(Xin. genfis2 accomplishes this by extracting a set of rules that models the data behavior. • radii is a vector that specifies a cluster center’s range of influence in each of the data dimensions.
genfis2 dimension are to be scaled from the range [1 +1].5) This is the minimum number of arguments needed to use this function. then 0. and 0. then the data in the first column of Xin are scaled from [10 +10]. • options is an optional vector for specifying algorithm parameters to override the default values.Xout.5 is specified for all data dimensions. Suppose Xin has two columns and Xout has one column. Here a range of influence of 0. Default values are in place when this argument is not specified. the data in the second column of Xin are scaled from [5 +5].5. and the data in Xout are scaled from [0 20].3 is the range of influence for the Xout data dimension. then xBounds defaults to the minimum and maximum data values found in each data dimension. Suppose Xin has two columns and Xout has one column. 10 5 20]) This specifies how to normalize the data in Xin and Xout into values in the range [0 1] for processing. If xBounds is an empty matrix or not provided. fismat = genfis2(Xin.25 0.[0.Xout. fismat = genfis2(Xin. Examples fismat = genfis2(Xin.5 and 0.5 0. See Also subclust 339 . These parameters are explained in the help text for subclust on page 372.[10 5 0.0.Xout.3]) This assumes the combined data dimension is 3.25 are the ranges of influence for each of the Xin data dimensions.0.
gensurf(fis) gensurf(fis.inputs.grids.refinput) can be used if there are more than two outputs.inputs. by the vector. respectively.refinput) gensurf(fis) generates a plot of the output surface of a given fuzzy inference system (fis) using the first two inputs and the first output.z]=gensurf(. horizontal) and Y (second.output) gensurf(fis. [x. If grids is a two element vector. output.grids. vertical) directions.. and the scalar. gensurf(fis.grids) allows you to specify the number of grids in the X (first.inputs.y.output.inputs.. 340 . gensurf(fis. the grids in the X and Y directions can be set independently. The length of the vector refinput is the same as the number of inputs.output.output. inputs. • Enter real double scalars to fix the values of other inputs. Description • Enter NaNs for the entries of refinput corresponding to the inputs whose surface is being displayed. gensurf(fis.inputs.output) generates a plot using the inputs (one or two) and output (only one is allowed) given.gensurf Purpose Synopsis 3gensurf Generate an FIS output surface.) returns the variables that define the output surface and suppresses automatic plotting.
2. See Also evalfis. generates the surface of a threeinput FIS named Temp from its first two inputs to its first output.[1 2].1. gensurf(a) 25 20 tip 15 10 5 10 8 6 4 2 food 0 0 2 service 6 4 8 10 Example 2 a = gensurf(Temp.[20 20].gensurf Example 1 a = readfis('tipper').2]).[nan nan 0. surfview 341 . while fixing a reference value for the third input at .
'vartype'.varindex. With this one function you can learn about every part of the fuzzy inference system.'vartype'. for input 1. 342 . The arguments for getfis are as follows: • a: the name of a workspace variable FIS structure.varindex. • 'mf': a required string that indicates you are searching for membership function information. getfis(a) getfis(a.mfindex.'mf'. • 'vartype': a string indicating the type of variable you want (input or output).'fisprop') getfis(a.getfis Purpose Synopsis 3getfis Get fuzzy system properties.'vartype'. for example).mfindex) getfis(a.'varprop') getfis(a. • mfindex: the index of the membership function for which you are seeking information.varindex.'mf'.'mfprop') Description This is the fundamental access function for the FIS structure. • varindex: an integer indicating the index of the variable you want (1.
'input'.1) Name = service NumMFs = 3 MFLabels = poor good excellent Range = [0 10] Four input arguments getfis(a.'type') ans = mamdani Three input arguments (output is the empty set) getfis(a.1.'name') ans = service 343 .'input'. 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 Two input arguments getfis(a.getfis Examples One input argument (output is the empty set) a = readfis('tipper').
'mf'. showfis 344 .'name') ans = good See Also setfis.2.5000 5.'input'.1.2) Name = good Type = gaussmf Params = 1.'mf'.1.0000 Six input arguments getfis(a.'input'.getfis Five input arguments getfis(a.
2. subplot(2. title('Sugeno system (Output 1)'). Examples mam_fismat = readfis('mam22. title('Sugeno system (Output 2)'). 2). gensurf(sug_fismat. title('Mamdani system (Output 2)').2). gensurf(sug_fismat. [1 2]. 1). 1). gensurf(mam_fismat. subplot(2. [1 2]. [1 2]. subplot(2. 2).4). The returned Sugeno system has constant output membership functions.2.2. The antecedent remains unchanged.fis'). subplot(2.2. These constants are determined by the centroids of the consequent membership functions of the original Mamdani system. title('Mamdani system (Output 1)').3).mam2sug Purpose Synopsis Description 3mam2sug Transform Mamdani FIS into a Sugeno FIS. sug_fis=mam2sug(mam_fis) mam2sug(mam_fis) transforms a (not necessarily single output) Mamdani FIS structure mam_fis into a Sugeno FIS structure sug_fis.1). sug_fismat = mam2sug(mam_fismat). gensurf(mam_fismat. [1 2]. 345 .
trapmf. evalmf.2 0.mfp2)) 1 0.x.5 1 1.5 2 2.1 0 0 0.gbellmf(x. gaussmf. gbellmf. plot(x. the transformed membership function will not look the same as it did originally. psigmf. sigmf.outType) This function translates any builtin membership function type into another.3 0. The input arguments for mf2mf are as follows: • inParams: the parameters of the membership function you are transforming • inType: a string name for the type of membership function you are transforming • outType: a string name for the new membership function you are transforming to Examples x=0:0. trimf.1:5. mfp1 = [1 2 3]. In principle. in terms of its parameter set. outParams = mf2mf(inParams. gauss2mf.trimf(x. smf.9 0.8 0.inType.'trimf').mf2mf Purpose Synopsis Description 3mf2mf Translates parameters between membership functions.5 3 3. mfp2 = mf2mf(mfp1.'gbellmf'.4 0.6 0.5 5 See Also dsigmf. Occasionally this translation results in lost information.5 4 4. pimf. so that if the output parameters are translated back into the original membership function type.5 0.mfp1).7 0. zmf 346 . mf2mf mimics the symmetry points for both the new and old membership functions.
for a FIS structure. mfedit(a) operates on a MATLAB workspace variable. the type. mfedit alone brings up the membership function editor with no FIS loaded. 347 .mfedit Purpose Synopsis 3mfedit Membership function editor. although of course you can always create your own specialized versions. mfedit('a') mfedit(a) mfedit Description mfedit('a') generates a membership function editor that allows you to inspect and modify all the membership functions for your FIS stored in the file. a. Eleven builtin membership functions are provided for you to choose from. For each membership function you can change the name. and the parameters. a. Refer to “The Membership Function Editor” on page 252 for more information about how to use mfedit.fis.
Select membership functions by clicking once on them or their labels. to add a customized membership function to the current variable. and so on.. select: Add MF. to add membership functions to the current variable. The File menu for the Membership Function Editor is the same as the one found on the FIS Editor.. View rules. Remove all MFs to delete all membership functions of the current variable.mfedit Select the icon for the variable on the upper left side of the diagram (under the heading “FIS Variables”) to display its associated membership functions in the plot region. to invoke the Surface Viewer. Add custom MF. View surface. open and save systems. • Under Edit... select: Edit FIS properties. Menu Items On the Membership Function Editor. to invoke the Rule Viewer.... ruleview.. there is a menu bar that allows you to open related GUI tools.. Refer to fuzzy on page 329 for more information. to invoke the Rule Editor. Remove current MF to delete the current membership function. Undo to undo the most recent change.. Edit rules.. ruleedit. fuzzy. surfview 348 . Membership Function Popup Menu See Also There are 11 builtin membership functions to choose from. to invoke the FIS Editor.. • Under View. and you also have the option of installing a customized membership function.
writefis 349 .. Examples The following example shows what the defaults are for each of the methods: a=newfis('newsys').andMethod. and the output argument is an FIS structure. • andMethod. . aggMethod.orMethod.newfis Purpose Synopsis Description 3newfis Create new FIS. orMethod. aggMethod. • fisType is the type of FIS. OR. The seven input arguments are as follows: • fisName is the string name of the FIS structure.fisType. aggregation. and defuzzMethod. 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. impMethod.defuzzMethod) This function creates new FIS structures. newfis has up to seven input arguments.. a=newfis(fisName.impMethod. and defuzzification.fis you create. fisName. respectively provide the methods for AND. implication.
ruleedit. has any rules initially. showrule(a2) ans = 1.txtRuleList) fis2 = parsrule(fis. ruleTxt = 'if service is poor then tip is generous'.” The default format is “verbose”. fis2. showrule Examples See Also 350 . If the original input FIS structure. The key language words in English are: if.'verbose'). lang. is used.ruleFormat. 'francais'. OR. a = readfis('tipper'). they are replaced in the new structure.txtRuleList. lang. then.lang) Description This function parses the text that defines the rules (txtRuleList) for a MATLAB workspace FIS variable. fis.ruleTxt. and returns a FIS structure with the appropriate rule list in place. This language must be either 'english'. is. If (service is poor) then (tip is generous) (1) addrule. a2 = parsrule(a. Three different rule formats (indicated by ruleFormat) are supported: 'verbose'. fis2 = parsrule(fis.” and “indexed. “symbolic.parsrule Purpose Synopsis 3parsrule Parse fuzzy rules. When the optional language argument.ruleFormat) fis2 = parsrule(fis. or 'deutsch'. AND. assuming the key words are in the language.txtRuleList. and NOT. fis. the rules are parsed in verbose mode.
y=pimf(x.[a b c d]) This splinebased curve is so named because of its Π shape.[1 4 5 10]). P=[1 4 5 10]') 1 0. gauss2mf.” x=0:0. gaussmf.pimf Purpose Synopsis Description 3pimf Π shaped builtin membership function. trapmf. zmf 351 . mf2mf.5 0. This membership function is evaluated at the points determined by the vector x. P = [1 4 5 10] 8 10 Examples See Also dsigmf.1:10. y = pimf(x. smf. psigmf. evalmf. gbellmf. trimf. The parameters a and d locate the “feet” of the curve.75 0.25 0 0 2 4 6 pimf.y) xlabel('pimf. sigmf. while b and c locate its “shoulders. plot(x.
while outputs and their membership functions appear on the right. fismat. a = readfis('tipper'). plotfis(fismat) This function displays a high level diagram of an FIS. plotfis(a) Examples See Also evalmf.plotfis Purpose Synopsis Description 3plotfis Plot an FIS. Inputs and their membership functions appear to the left of the FIS structural characteristics. plotmf 352 .
and varIndex.1) poor good excellent Examples 1 0. plotmf(fismat.varType.2 0 0 1 2 3 4 5 service 6 7 8 9 10 See Also evalmf.6 0.varIndex) This function plots all of the membership functions in the FIS called fismat associated with a given variable whose type and index are respectively given by varType ('input' or 'output').8 Degree of belief 0. a = readfis('tipper'). plotfis 353 . plotmf(a.4 0. This function can also be used with the MATLAB function.'input'.plotmf Purpose Synopsis Description 3plotmf Plot all of the membership functions for a given variable. subplot.
mf2mf.5 0. P=[2 3 5 8]') 1 0. plot(x. trimf.a. a2.75 0.[a1 c1 a2 c2]) The sigmoid curve plotted for the vector x depends on two parameters a and c as given by 1 f ( x . Examples x=0:0. gaussmf. y = psigmf(x. trapmf.25 0 0 2 4 6 psigmf. c ) = ) –a ( x – c 1+e psigmf is simply the product of two such curves plotted for the values of the vector x f1(x.psigmf Purpose Synopsis Description 3psigmf Builtin membership function composed of the product of two sigmoidallyshaped membership functions. gbellmf.[2 3 5 8]).1:10. c2) The parameters are listed in the order: [a1 c1 a2 c2]. P = [2 3 −5 8] 8 10 See Also dsigmf. pimf. gauss2mf. y=psigmf(x. evalmf. a1. smf. c1) * f2(x. sigmf.y) xlabel('psigmf. zmf 354 .
Examples fismat = readfis('tipper'). fismat = readfis (no input arguments) brings up a uigetfile dialog box to assist with the name and directory location of the file.fis file (named filename) on the disk and bring the resulting file into the workspace.readfis Purpose Synopsis Description 3readfis Load an FIS from the disk. 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 355 . fismat = readfis('filename') Read a fuzzy inference system from a .
1) returns Name = temperature NumMFs = 0 MFLabels = Range = [0 100] See Also addmf. getfis(b.varType. from the fuzzy inference system associated with the workspace FIS structure.1. mfIndex.[0 100]). addvar. a = addvar(a. • mfIndex is an integer for the index of the membership function. This index represents the order in which the variables are listed.'input'.'varType'.1) returns Name = temperature NumMFs = 1 MFLabels = cold Range = [0 100] b = rmmf(a.'input'.mfIndex) fis = rmmf(fis. Examples a = newfis('mysys').varIndex. getfis(a. • The argument 'mf' is a string representing the membership function. plotmf.rmmf Purpose Synopsis Description 3rmmf To remove membership function from an FIS. fis = rmmf(fis.'mf'.[0 30 60]).'mf'.1.'input'. fis: • The string varType must be 'input' or 'output'.'temperature'.'input'. varType. addrule. a = addmf(a.'input'.'mf'.varIndex. • varIndex is an integer for the index of the variable.'cold'. This index represents the order in which the membership functions are listed. rmvar 356 .'trimf'.1).mfIndex) removes the membership function. of index varIndex. of variable type.
'varType'. Examples a = newfis('mysys'). of index varIndex.errorStr] = rmvar(fis.errorStr] = rmvar(fis. [fis2. fis: • The string varType must be 'input' or 'output'.varIndex) returns any error messages to the string. from the fuzzy inference system associated with the workspace FIS structure. This command automatically alters the rule list to keep its size consistent with the current number of variables. getfis(a) 357 .varIndex) fis2 = rmvar(fis.'varType'. before removing it. [fis2.'temperature'. • varIndex is an integer for the index of the variable. a = addvar(a. You cannot remove a fuzzy variable currently in use in the rule list.'varType'. This index represents the order in which the variables are listed.[0 100]).rmvar Purpose Synopsis Description 3rmvar To remove variables from an FIS.varIndex) removes the variable 'varType'.varIndex) fis2 = rmvar(fis. You must delete from the FIS any rule that contains a variable you want to remove. errorStr.'input'.'varType'.
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.rmvar 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'. rmmf 358 . addvar. addrule.
Formats are verbose. is used to modify the rules of an FIS structure stored in a file. a. and weights. The Rule Editor. To use this editor to create rules. ruleedit('a') ruleedit(a) Language and Format are options on this GUI. 359 . The syntax ruleedit(a) is used when you want to operate on a workspace variable for an FIS structure called a.fis. You can create the rules using the listbox and check box choices for input and output variables. Refer to “The Rule Editor” on page 256 for more information about how to use ruleedit. and indexed. you must first define all of the input and output variables you want to use with the FIS editor. and Francais. symbolic. when invoked using ruleedit('a'). Languages are English.ruleedit Purpose Synopsis Description 3ruleedit Rule editor and parser. Deutsch. connections. It can also be used to inspect the rules being used by a fuzzy inference system.
mfedit.” and so on to create actual sentences. ` symbolic substitutes some symbols for the words used in the verbose mode.. • Use the following Edit menu item: Undo to undo the most recent change. For example. open and save systems.” ` indexed mirrors how the rule is stored in the FIS structure. Deutsch. View surface. to invoke the Rule Viewer. fuzzy.. surfview 360 . to invoke the Surface Viewer.” “then. and so on. to invoke the FIS Editor... to invoke the Membership Function Editor. Refer to fuzzy on page 329 for more information. showrule. See Also addrule. and Francais Format to select the format: ` verbose uses the words “if.ruleedit Menu Items On the Rule Editor. Edit membership functions. View rules.” “OR.” “AND.... • Use the Options menu items: Language to select the language: English. parsrule. • Use the following View menu items: Edit FIS properties. there is a menu bar that allows you to open related GUI tools. “if A AND B then C” becomes “A & B => C.. ruleview. The File menu for the Rule Editor is the same as the one found on the FIS Editor.
Menu Items On the Rule Viewer. It is used to view the entire implication process from beginning to end. The File menu for the Rule Viewer is 361 . a.ruleview Purpose Synopsis Description 3ruleview Rule viewer and fuzzy inference diagram. You can move around the line indices that correspond to the inputs and then watch the system readjust and compute the new output. Refer to “The Rule Viewer” on page 259 for more information about how to use ruleview.fis. open and save systems. there is a menu bar that allows you to open related GUI tools. and so on. ruleview('a') The Rule Viewer invoked using ruleview('a') depicts the fuzzy inference diagram for an FIS stored in a file.
.. the rule associated with that number will appear in the Status Bar at the bottom of the Rule Viewer. If you click on the rule numbers on the left side of the fuzzy inference diagram. to invoke the Surface Viewer • Use the Options menu item: Rule display format to set the format in which the rule appears.. Refer to fuzzy on page 329 for more information. to invoke the Membership Function Editor Edit rules.ruleview the same as the one found on the FIS Editor. to invoke the Rule Editor View surface. • Use the View menu items: Edit FIS properties.. ruleedit.. to invoke the FIS Editor Edit membership functions.. surfview 362 . See Also fuzzy... mfedit.
five.mfindex. indicating this variable is a membership function • mfindex — the index of the membership function belonging to the chosen variable • 'fispropname' — a string indicating the property of the FIS field you want to set: name. or an array describing the range of the parameters (for params) 363 .'newfisprop') a = setfis(a. a = setfis(a.'mf'. or params. aggmethod.'vartype'.varindex. ormethod. Description The command setfis can be called with three. depending on whether you want to set a property of the entire FIS structure. or an array describing the range of that variable (for range) • 'mfpropname'— a string indicating the name of the membership function field you want to set: name. defuzzmethod • 'newfisprop' — a string describing the name of the FIS property or method you want to set • 'varpropname' — a string indicating the name of the variable field you want to set: name or range • 'newvarprop' — a string describing the name of the variable you want to set (for name).. or for a particular membership function belonging to one of those variables.setfis 3 3setfis Purpose Synopsis Set fuzzy system properties. for a particular variable belonging to that FIS structure.'varpropname'.'fispropname'. impmethod..'newvarprop') a = setfis(a.'vartype'. andmethod. type. The arguments are: • a — a variable name of an FIS from the workspace • 'vartype' — a string indicating the variable type: input or output • varindex — the index of the input or output variable • 'mf' — a required string for the fourth argument of a 7argument call for setfis.varindex.'newmfprop'). or seven input arguments. 'mfpropname'. • 'newmfprop' — a string describing the name or type of the membership function field want to set (for name or type). . type.
'input'.'help').'input'. a2 = setfis(a.1. getfis(a2.setfis Examples Called with three arguments. getfis(a2.'name') ans = help If used with seven arguments. setfis will update any of several membership function properties.2.1. setfis will update two variable properties.'mf'. 'name'.'mf'.'input'.'name') ans = wretched See Also getfis 364 . a2 = setfis(a.1.2. Results in out = eating If used with five arguments.'input'.'wretched'). 'eating').1. 'name'). a2 = setfis(a.'name'.'name'. getfis(a2. a = readfis('tipper').
This means. and flag are standard Simulink Sfunction arguments (see Chapter 8. which it then continues to use until the simulation is complete.u. there are two inputs to fismat. See Also evalfis. x.x. The arguments t.sffis Purpose Synopsis Description 3sffis Fuzzy inference Sfunction for Simulink. among other things. then u will be a twoelement vector. that sffis builds a data structure in memory during the initialization phase of a Simulink simulation. fuzblock 365 .fismat) This MEXfile is used by Simulink to undertake the calculation normally performed by evalfis. The argument u is the input to the MATLAB workspace FIS structure. It has been optimized to work in the Simulink environment. for example. output = sffis(t. fismat.flag. If. “SFunctions” in the Using Simulink documentation).
14. Name Type Inputs/Outputs NumInputMFs NumOutputMFs NumRules AndMethod OrMethod ImpMethod AggMethod DefuzzMethod InLabels OutLabels InRange OutRange InMFLabels tipper mamdani [2 1] [3 2] 3 3 min max min max centroid service food tip [0 10] [0 10] [0 30] poor good excellent rancid delicious cheap average generous gaussmf gaussmf OutMFLabels InMFTypes 366 . 18. 12. 27. 4. Examples a = readfis('tipper'). 13. 11. 17. 19. 10. 3. 24. 15. 2. 22. 8. 20. 6. allowing you to see the significance and contents of each field of the structure. 16. 7.showfis Purpose Synopsis Description 3showfis Display annotated FIS. 5. 23. showfis(a) returns 1. 9. 25. showfis(fismat) showfis(fismat) prints a version of the MATLAB workspace variable FIS. 21. 26. fismat.
44. 43. 43. 29. 42. 31. 42. OutMFTypes InMFParams OutMFParams Rule Antecedent Rule Consequent Rule Weigth Rule Connection gaussmf trapmf trapmf trimf trimf trimf [1. 43. 44. 33. 38.5 0 0 0] [1. 32.5 5 0 0] [1.5 10 0 0] [0 0 1 3] [7 9 10 10] [0 5 10 0] [10 15 20 0] [20 25 30 0] [1 1] [2 0] [3 2] 1 2 3 1 1 1 2 1 2 See Also getfis 367 . 42. 34. 43. 41. 35. 40. 30. 36. 39. 42. 44. 44. 37.showfis 28.
format. When used with four arguments. It can be invoked with one to four arguments.format. 'symbolic'. The second (optional) argument indexList is the vector of rules you want to display. for which English is the default language).lang) displays the rules in the language given by lang. and showrule(fis. The first argument. This is the MATLAB workspace variable name for a FIS structure. which must be either 'english'. 'francais'. the forth argument must be verbose. showrule(fis) showrule(fis.showrule Purpose Synopsis 3showrule Display FIS rules.format) showrule(fis.indexList. and 'indexed'. 368 .indexList.indexList) showrule(fis.indexList. The third argument (optional) is the string representing the format in which the rules are returned. is required.Lang) Description This command is used to display the rules associated with a given system. for membership function index referencing. showrule can return the rule in any of three different formats: 'verbose' (the default mode. or 'deutsch'. fis.
2 (1) : 1 3 2. (service==poor)  (food==rancid) => (tip=cheap) (1) showrule(a. addrule 369 .1:3.'symbolic') ans = 3. If (service is good) then (tip is average) (1) showrule(a. (service==excellent)  (food==delicious) => (tip=generous) (1) 1.'indexed') ans = 1 1. 3 (1) : 2 See Also parsrule.showrule Examples a = readfis('tipper').2) ans = 2.[3 1]. If (service is poor) or (food is rancid) then (tip is cheap) (1) showrule(a. showrule(a. ruleedit.1) ans = 1. 1 (1) : 2 2 0.
and thus is appropriate for representing concepts such as “very large” or “very negative.[a c]) The sigmoidal function. is a mapping on a vector x. y = sigmf(x. c ). You can find out more about this in this chapter’s entries for dsigmf and psigmf.y) xlabel('sigmf. c ) = ) –a ( x – c 1+e Depending on the sign of the parameter a.1:10. a. and depends on two parameters a and c: 1 f ( x. psigmf. trimf. evalmf. as given below by f ( x. plot(x. y=sigmf(x.5 0.” More conventionallooking membership functions can be built by taking either the product or difference of two different sigmoidal membership functions. zmf 370 .25 0 0 2 4 6 sigmf. smf.75 0. P=[2 4]') 1 0. P = [2 4] 8 10 See Also dsigmf. gbellmf. Examples x=0:0.sigmf Purpose Synopsis Description 3sigmf Sigmoidallyshaped builtin membership function. trapmf. gaussmf.[a c]). the sigmoidal membership function is inherently open to the right or to the left. a.[2 4]). pimf. sigmf(x. mf2mf. gauss2mf.
[a b]) This splinebased curve is a mapping on the vector x. x=0:0. y=smf(x. trimf. and is named because of its S–shape. P = [1 8] 8 10 Examples See Also dsigmf. mf2mf. pimf. trapmf. gauss2mf.y) xlabel('smf.25 0 0 2 4 6 smf. y = smf(x.1:10. The parameters a and b locate the extremes of the sloped portion of the curve. evalmf.5 0.75 0. zmf 371 . plot(x. P=[1 8]') 1 0. gaussmf. gbellmf.[1 8]). sigmf. psigmf.smf Purpose Synopsis Description 3smf S–shaped builtin membership function.
S] = subclust(X.e.xBounds. then the scalar value is applied to all data dimensions. The first row contains the minimum axis range values and the second row contains the maximum axis range values for scaling the data in each dimension. [C. For example. if the data dimension is two (X has two columns). in order to determine the next data cluster and its center location • Iterates on this process until all of the data is within radii of a cluster center The subtractive clustering method is an extension of the mountain clustering method proposed by R. i. This argument is optional if X is already normalized. each cluster center will have a spherical neighborhood of influence with the given radius.subclust Purpose Synopsis Description 3subclust Find cluster centers with subtractive clustering. The algorithm • Selects the data point with the highest potential to be the first cluster center • Removes all data points in the vicinity of the first cluster center (as determined by radii). The variable radii is a vector of entries between 0 and 1 that specifies a cluster center’s range of influence in each of the data dimensions. xBounds is a 2byN matrix that specifies how to map the data in X into a unit hyperbox.25] specifies that the range of influence in the first data dimension is half the width of the data space and the range of influence in the second data dimension is one quarter the width of the data space. The subtractive clustering method assumes each data point is a potential cluster center and calculates a measure of the likelihood that each data point would define the cluster center. radii = [0.radii. For example.2 and 0.. 10 5] specifies that data values in the first data dimension are to be scaled from the range [10 +10] into values in the range [0 1].5. If radii is a scalar. each row of X is a data point. If xBounds is an empty 372 . data values in the second data dimension are to be scaled from the range [5 +5] into values in the range [0 1]. Small radii values generally result in finding a few large clusters. assuming the data falls within a unit hyperbox. Good values for radii are usually between 0.5 0.options) This function estimates the cluster centers in a set of data by using the subtractive clustering method. Yager. where N is the data dimension. based on the density of surrounding data points. xBounds = [10 5. The matrix X contains the data to be clustered.
5 0.0.5) • options(3) = rejectRatio : This sets the potential. then xBounds defaults to the minimum and maximum data values found in each data dimension.[]. 0. A range of influence of 0. The returned S vector contains the sigma values that specify the range of influence of a cluster center in each of the data dimensions. then progress information will be printed as the clustering process proceeds. (default: 0. The squashFactor is set to 2. respectively. as a fraction of the potential of the first cluster center.0. All cluster centers share the same set of sigma values. (default: 1.[0.S] = subclust(X.25 0. indicating that we will only accept data points that have a very strong potential for being cluster centers.8 0.7]) This assumes the data dimension is 3 (X has 3 columns) and uses a range of influence of 0. (default: 0) The function returns the cluster centers in the matrix C.8. and 0. each row of C contains the position of a cluster center. indicating that we only want to find clusters that are far from each other. so as to quash the potential for outlying points to be considered as part of that cluster. above which another data point will be accepted as a cluster center.[2.subclust matrix or not provided. [C. The acceptRatio is set to 0. (default: 0. These components of the vector options are specified as follows: • options(1) = quashFactor : This is the factor used to multiply the radii values that determine the neighborhood of a cluster center. as a fraction of the potential of the first cluster center. The options vector can be used for specifying clustering algorithm parameters to override the default values.S] = subclust(X. below which a data point will be rejected as a cluster center.25) • options(2) = acceptRatio: This sets the potential.5) This is the minimum number of arguments needed to use this function.15) • options(4) = verbose: If this term is not zero. second and third data dimension.3 for the first. The scaling factors for mapping the data into a unit hyperbox will be obtained from the minimum and maximum data values.25.5.5 has been specified for all data dimensions. Examples [C.3].0 0. The 373 .
subclust rejectRatio is set to 0. 1994. Vol. Filev. 209219. No. pp. R. indicating that we want to reject all data points without a strong potential.. 2. 2.” Journal of Intelligent & Fuzzy Systems. 1994. “Fuzzy Model Identification Based on Cluster Estimation. Yager. No. “Generation of Fuzzy Rules by Mountain Clustering. 3.” Journal of Intelligent & Fuzzy Systems. 3. 374 . Vol. and D. Sept.7. S. See Also References genfis2 Chiu.
as well the output variable you want assigned to the output (or Z) axis. 375 . Using the popup menus. you can manipulate the surface so that you can view it from different angles.surfview Purpose Synopsis Description 3surfview Output surface viewer. surfview('a') The Surface Viewer invoked using surfview('a') is a GUI tool that lets you examine the output surface of an FIS stored in a file.fis. By clicking on the plot axes and dragging the mouse. Select the Evaluate button to perform the calculation and plot the output surface. If there are more than two inputs to your system. Since it does not alter the fuzzy system or its associated FIS structure in any way. for any one or two inputs. a. Refer to “The Surface Viewer” on page 261 for more information about how to use surfview. you select the two input variables you want assigned to the two input axes (X and Y). you must supply the constant values associated with any unspecified inputs in the reference input section. it is a readonly editor.
to invoke the Rule Editor. ruleedit. to invoke the FIS Editor. fuzzy. to invoke the Membership Function Editor... and so on. See Also anfisedit..surfview Menu Items On the Surface Viewer. View rules. This is the default option. to invoke the Rule Viewer. • Use the View menu items: Edit FIS properties.. open and save systems. Edit rules.. Color Map to choose among several different color schemes.. there is a menu bar that allows you to open related GUI tools. To deselect this option. ruleview 376 . mfedit. The File menu for the Surface Viewer is the same as the one found on the FIS Editor. • Use the Options menu items: Plot to choose among eight different kinds of plot styles. select it once more. Refer to fuzzy on page 329 for more information.. gensurf.. Always evaluate to automatically evaluate and plot a new surface every time you make a change that affects the plot (like changing the number of grid points). Edit membership functions.
and depends on four scalar parameters a. y = trapmf(x.a.c ≤ x ≤ d . b.trapmf Purpose Synopsis Description 3trapmf Trapezoidalshaped builtin membership function. b. d ) = 0. as given by f ( x .y) xlabel('trapmf. and d. 1. P=[1 5 7 8]') 1 0. more compactly.. c.5 0.. b ≤ x ≤ c d–x . c.a. x≤a x–a .25 0 0 2 4 6 trapmf. P = [1 5 7 8] 8 10 377 . c. plot(x.75 0. b. d–c 0.a ≤ x ≤ b . by x–a d–x f ( x . d≤x or. d ) = max min . x.” Examples x=0:0. . b–a 1. y=trapmf(x. 0 b – a d – c The parameters a and d locate the “feet” of the trapezoid and the parameters b and c locate the “shoulders.[1 5 7 8]).1:10.[a b c d]) The trapezoidal curve is a function of a vector.
trapmf See Also dsigmf. mf2mf. gbellmf. evalmf. zmf 378 . trimf. gauss2mf. gaussmf. sigmf. smf. psigmf. pimf.
b ≤ x ≤ c c–b 0. P=[3 6 8]') 1 0. y = trimf(x. as given by f ( x . by x–a c–x f ( x . 0 b – a c – b The parameters a and c locate the “feet” of the triangle and the parameter c locates the peak.25 0 0 2 4 6 trimf. more compactly. .trimf Purpose Synopsis Description 3trimf Triangularshaped builtin membership function.[3 6 8]).. x≤a x–a .a ≤ x ≤ b . c ) = 0.params) y = trimf(x. P = [3 6 8] 8 10 379 . y=trimf(x. c ) = max min . b–a c–x . b.y) xlabel('trimf. and c.. c≤x or..[a b c]) The triangular curve is a function of a vector.a. b.5 0. Examples x=0:0. and depends on three scalar parameters a. x.a.75 0. b.1:10. plot(x.
gbellmf. sigmf. trapmf 380 . mf2mf. gauss2mf. pimf. evalmf. smf. gaussmf. psigmf.trimf See Also dsigmf.
writefis(fismat) brings up a dialog box to assist with the naming and directory location of the file. as a .'service'. No dialog box is used and the file is saved to the current directory. Examples a = newfis('tipper').'gaussmf'.'filename'. The extension .'excellent'. a = addmf(a. a = addmf(a.1.'input'.'poor'.'dialog') brings up a dialog box with the default name filename. writefis(fismat. writefis(fismat.[1.5 10]). fismat.'input'.fis is only added to filename if it is not already included in the name.'good'.fis file on Description disk.'input'.'dialog' writefis saves a MATLAB workspace FIS structure. fismat.[0 10]).'input'.[1.'gaussmf'. to a disk file called filename.5 0]).5 5]).[1.fis.'my_file') readfis See Also 381 .'filename') writes a .fis supplied.writefis Purpose Synopsis 3writefis Save an FIS to the disk. writefis(fismat) writefis(fismat.'filename') writefis(fismat. writefis(a.'gaussmf'.'filename'. a = addvar(a.1.1.fis file corresponding to the FIS structure. a = addmf(a.
x=0:0.75 0. mf2mf. pimf. y = zmf(x.1:10. trimf 382 . gauss2mf. y=zmf(x. P = [3 7] 8 10 See Also dsigmf. sigmf. The parameters a and b locate the extremes of the sloped portion of the curve. evalmf. plot(x. gaussmf. P=[3 7]') 1 0. smf.zmf Purpose Synopsis Description Examples 3zmf Zshaped builtin membership function. trapmf.[3 7]).5 0.y) xlabel('zmf. psigmf. gbellmf.[a b]) This splinebased function of x is so named because of its Zshape.25 0 0 2 4 6 zmf.
91 matrix 73 saving a FIS 62 structure 93. 322 findcluster 128. 36 addrule 72. 37. 109. 132. 86. 132 fuzzy 329 fuzzy clustering 115. 23. 73. 109. 326 evalmf 321 F fcm (fuzzy cmeans) 120. 125. 117 Sugenotype 86. 49. 118 checking error 119 clustering 120. 59. 84. 86. 88. 45. 132 antecedent 37 convertfis 316 D defuzz 317 defuzzification 32. 95 Sugenotype See also Sugenotype inference 97 fuzblock 83. 41 degree of membership 20. 120 fuzzy cmeans clustering 322 Fuzzy Inference System (FIS) 19. 128. 74. 132 fuzzy operators 29. 114. 132 defuzzify 32. 133 AND 30. 59. 60. 49. 49. 33. 38 distfcm 121 FIS 43. 65. 104. 125. 40. 86. 37. 39. 40. 86. 121. 310 Ccode 130 Editor 45. 95. 40. 45. 63. 112. 115 files 76 generating 100 Mamdanitype 49. 44. 44. 126. 88. 95. 114. 76. 109. 93. 106. 92. 42. 37. 63. 314 antecedent 35. 53. 86. 35. 76. 35. 32. 132 E error tolerance 104 evalfis 73. 36. 49. 71. 92. 88. 67. 131 fuzzy set 20. 60. 103 ANFIS 93 anfis 7. 95. 38 addvar 76. 128. 327 fuzdemos 328 fuzzification 32. 58. 37. 63. 74. 324 B backpropagation 104 C chaotic time series 120 checking data 94. 58. 26. 92. 63. 132 I1 .Index A addmf 72. 35. 132. 39 dsigmf 27. 132 clustering algorithms 133 clustering GUI 128 consequent 32. 310 options 116 ANFIS Editor GUI 7. 319. 47. 318 aggregation 36. 314 anfisedit 67. 38. 115. 68. 95. 24. 40. 95.
98 I ifthen rules 32 antecedent 32 consequent 32 implication 32. 63. 37. 86. 336 genfis2 101. 103 L logical operations 28 P parsrule 350 pimf 28. 133 mf editor 103 Membership Function Editor 45. 90. 349 NOT 30. 354 I2 . 52 membership functions bell 27 custom 63 Gaussian 27 Pi 27 S 27 sigmoidal 27 Z 27 MF See also membership function mf2mf 346 mfedit 347 min 43 model validation 94. 338 gensurf 70. 55. 35. 334 gbellmf 27. 133 initfcm 121 N neurofuzzy inference 93 newfis 72. 89.Index G gauss2mf 27. 90 max 41. 43 probabilistic OR 39 probor 41 psigmf 27. 60. 53. 86 implication See also ifthen rules 32. 103 O OR 30. 351 plotfis 68. 126. 37. 28. 352 plotmf 68. 118. 39. 340 getfis 66. 342 glossary 132 grid partition 100 H hybrid method 104 membership function 23. 335 genfis 111 genfis1 101. 88. 332 gaussian 27 gaussmf 27. 90. 35. 353 M mam2sug 345 Mamdani’s method 36 Mamdanistyle inference 133 Mamdanitype inference 35. 47. 76. 43. 49. 43.
377 trimf 379 Rule Editor 45.field syntax 66. 76. 366 showrule 368 sigmf 27. 73 subclust 372 subtractive clustering 100. 73. 88. 357 surfview 375 T Tconorm 31. 371 standalone Ccode 130 standalone fuzzy inference engine 130 step size 117 structure. 86. 128 Sugeno 123 Sugenotype FIS See also Sugenotype inference 101 Sugenotype inference 37. 356 rmvar 76. 61 Z zmf 28. 45. 133 training data 95. 365 showfis 67. 115 training error 117 trapezoidal 26 trapmf 26. 355 rmmf 76. 47. 120. 363 sffis 84. 88. 56 rule formats 315. 123. 360 Rule Viewer 45. 97 Tnorm 31. 74. 59 ruleedit 359 ruleview 361 S setfis 66. 99. 50.Index R readfis 65. 124. 133 testing data 94. working with 78 singleton 36 sltank 79 smf 28. 47. 133 sum 41 Surface Viewer 45. 76. 382 I3 . 83 Simulink. 370 W writefis 381 Simulink blocks fuzzy controller with ruleviewer 81 Fuzzy Logic Controller 79.