You are on page 1of 65

FUZZY SYSTEMS:

Basics using MATLAB Fuzzy


Toolbox

By

Heikki N. Koivo
©

2006

1
2.1. Fuzzy sets
Membership functions

Universal discourse U set of elements, {u}.

Fuzzy set F in universal discourse U:

Membership function µF (membership function).

µF :U →[0,1]
Fuzzy set
F = {x, µ F ( x) x ∈ U }
The value of the membership function µF(u) describes the
degree of membership of u in the fuzzy set F. It takes values
between 0 and 1.
µ(u) bellshaped triangular trapezoidal singleton
1

Fig.2. 1. Membership functions may assume different


shapes like bell-shaped, triangular, trapezoidal and
singleton.

2
2. 2. USING MATLAB Fuzzy Toolbox GUI
PROBLEM 2.1. Let the room temperature T be a fuzzy
variable. Characterize it with three different (fuzzy)
temperatures: cold,warm, hot.

SOLUTION:
1. First define the temperature range, e.g. [00,400].

2. When MATLAB is open, then open GUI (GUI =


Graphical User Interface)
by typing fuzzy
1. Input membership
The result is shown below: functions
2. Fuzzy inference system
3. Output membership
functions

Fig.2.2. GUI of Fuzzy toolbox. Study the content of


GUI to have an overall understanding before
proceeding.

3
Next activate input membership block by moving mouse
on top of it and by clicking once. Activation is shown by
a red boundary on the block. If you click twice, the
MEMBERSHIP FUNCTION EDITOR opens up. This
is needed when defining membership functions.

Another way to do the same is to use View menu (cf.


Figure below). Input block is again activated first.

Fig.2.3. Editing membership functions from View


menu.

4
Fig.2.4. Display to edit input membership functions.

First change Range to the one given in the problem or to


[00,400]. This is done by moving the cursor to the Range
area and clicking once. Then you can correct the figures
in the range domain as you would correct text in a text
document. Note that you have to leave space between the
numbers.

Next click Close or anywhere in the light grey area above


with the mouse. The result is shown below.

5
Fig.2.5. Change the range of input variable to [00,400].

Now you are ready to define new membership functions.


Choose Add MF's from EDIT menu. The following
display is shown.

Fig.2.6. Type and number of membership functions can


be chosen.

6
Default value is three triangular (trimf) (3) membership
functions as seen on the display. These will divide the
range into three equal parts.

Click OK, if you are happy with the default values,


otherwise make your own choice. (Try e.g. five gaussian
membership functions. Different membership functions
can be found under MF type.)

The result is shown below. Note that the default names


for the membership functions are mf1, mf2 and mf3.

Fig.2.7. The result of choosing three, triangular


membership functions, which by default are named mf1,
mf2 and mf3.

7
2.3. Fuzzy set operations

Let A and B be two fuzzy sets in universal discourse U.


Their corresponding membership functions are

µA and µB.

The basic set operations union, intersection and


complement are defined by the membership functions as
follows:

Union

µ A∪ B (u ) = max{µ A (u ), µ B (u )}, ∀ u ∈ U

µ A∪B (u)
1
µ B (u )

µ A (u )

Fig.2. 8. The membership function of union u


A ∪ B is defined by taking the maximum of
membership functions of A and B.

8
Intersection
µ A∩ B (u ) = min{µ A (u ), µ B (u )}, ∀ u ∈ U

µ A∩ B
1 µ A (u ) µ B (u )

Fig.2.9. The membership function of intersection of


u fuzzy
sets A ∩ B is defined by taking the minimum of
membership functions of A or B.

Complement

The membership function of the complement of a fuzzy


set A, A is defined as follows

µ A (u ) = 1 − µ A (u ), ∀ u ∈ U

µ A (u ) µ A (u )
1

u
µ (u )
b ells hap ed t ria ngul ar tr apez oid al s in gleton
1

µ (u )
b ells hap ed t ria ngul ar tr apez oid al s in gleton
1

Fig.2.10. Membership functions of a fuzzy set A and its


complement A .

9
2.3. Fuzzy logical operations

The membership function of the logical operation or of


two fuzzy sets A and B is

µ A∨ B (u, v) = max{µ A (u ), µ B (v)}, u ∈ U ∧ v ∈ V

The membership function of the logical operation and of


two fuzzy sets A and B is

µ A∧ B (u , v) = min{µ A (u ), µ B (v)}, u ∈ U ∧ v ∈ V

The membership function of the logical operation not of


a fuzzy set A is

µ A (u ) = 1 − µ A (u ), u ∈ U

10
EXAMPLE

RULEBASE
Rule 1: If x is A1 and y is B1 then z is C1,
Rule 2: If x is A2 and y is B2 then z is C2.

Here A1, B1 and C1, A2, B2 and C2


are fuzzy sets.

Interpretation:
1. and corresponds to min
2. or corresponds to max
3. then corresponds to min

MORE GENERALLY
1. α i = T ( µ Ai ( x0 ), µ Bi ( y0 ))
2. µC ' ( z ) = T (α i , µCi ( z ))
i
To combine the rules
3. µC ( z ) = T ( µC1 ( z ), µC2 ( z ),..., µC N
*
( z ))

11
FUZZY INFERENCE (AND-OR)
µA ( x) µB ( y) µC ( z)
1 1
1 1 1

µC' 1 ()z µC (z)


1
0 0 0
x y z

µA2( x) µB 2( y) µC 2( z)
1 1 1

0
z
µ C' 2 ()z

0 0 0
x0 x y0 y min z

Evaluate the first rule


1. α1 = min( µ A1 ( x0 ), µ B1 ( y0 ))
2. µC ' ( z ) = min(α1, µC1 ( z ))
1
Evaluate the second rule
1. α 2 = min( µ A ( x0 ), µ B ( y0 ))
2 2
2. µ ' ( z ) = min(α 2 , µC ( z ))
C2 2
Combine both rules (Aggregate)
µC ' ( z ) = max( µC ' ( z ), µC ' ( z ))
1 2
Defuzzify
Compute the center of gravity

12
OUTPUT MEMBERSHIP FUNCTIONS
SINGLETONS

µA (x) µB (y) µC (z)


1 1 1
1 1 1

µC (z)
µ C' ( z)
1 1
0 0 0
x y z

µA (x) µB (y) µC (z)


2 2 2
1 1 1

0
z

µ C' ( z)
2

0 0 0
x0 x y0 y min z

13
FUZZY INFERENCE (PRODUCT)

14
2.3.1. T-norm

Triangular norm

Mapping T : [0,1]× [0,1] → [0,1] is called T-norm if

it satisfies the following criteria:

T (a, b) = T (b, a ) commutativity

T (T (a, b), c) = T (a, T (b, c)) associativity

a ≤ c ∧ b ≤ d = T ( a , b ) ≤ T ( c, d ) nondecreasing

T (a,1) = T (1, a ) = a , T (0,0) = 0 boundary

Example: Intersection of sets.

REMARK: In fuzzy control T-norm is used to connect


different propositions in connection of and-operation. The
arguments are then the corresponding membership
functions.

The most common T-norms are

1. Minimum min(a, b)

2. Product ba

15
2.3.2. T-conorm
Triangular conorm
Mapping T * : [0,1]× [0,1] → [0,1] is called T-conorm,

if it is T-norm and in addition satisfies

T * (a,0) = T * (0, a ) = a , T * (1,1) = 1

Example 2.2:
T-conorm is generally used to connect propositions in
connection of or-operation.
The most common T-conorms:

1. Maximum max(a, b)

2. In probability theory a+b-ab

3. For triangular membership functions sum (a+b) is used

(although it does not satisfy the above conditions)

16
2.4. Fuzzy reasoning

1. Generalized Modus Ponens (GMP)


(forward chaining)
2. Generalized Modus Tollens (GMT)
(backward chaining)

Example 2.3: Consider two fuzzy sets A and B, and their

complements A and B . Then

(GMP)

Fact 1: x is A

Premise 2: If x is A then y is B

Conclusion: y is B

(GMT)

Fact 1: y is B

Premise 2: If x is A then y is B

Conclusion: x is A

17
Example 2.4: Car driving

Distance
A d B
SAFE
DISTANCE

Fig.2.11. Cars A and B on a highway.

You are driving car A on a highway. You want to keep a


safe distance to car B in front of you. Design a (simplified)
fuzzy-logic system, which satisfies the requirements.

Proceed as follows:

a. Determine the required fuzzy variables (input/output)


and their ranges.

b. Form the rule base.

c. Use fuzzy reasoning to check the operability of the

rulebase.

18
SOLUTION:

a. Fuzzy variables. Start with a simple case.

INPUT: Distance d

OUTPUT: Breaking power b (gas pedal)

Three (3) membership functions are chosen for both input


and output.

Membership functions for INPUT:

Distance d (meters): short, medium, long.

Membership functions for OUTPUT:

Breaking power b (%): large, medium, none

We will use the fuzzy toolbox to define the fuzzy system by


giving numerical values for the variables indicated.

In MATLAB type

» fuzzy

This opens the GUI. Activate the input window.

19
Give a name to the fuzzy input variable. Call it distance. Click
Close.

Fig.2.12. Naming the input variable in GUI.

Next click the input block twice with mouse to open the
membership function window. First define the range, say
from 0 to 30 m/s.

20
Fig. 2.13. Set the range in GUI.

Next choose from Edit Add MFs. Pick the default values:
3 triangular membership functions. Give a name to each:
Call them high, medium, and short. When you are
finished, click Close.

21
Fig. 2.14. Three triangular membership functions have been
chosen for the input variable distance. The middle one has
been activated and renamed as medium.

Repeat the same procedure with the output b, breaking


power.

Define the name of the output, break, and its range. Use
three membership functions: hard, medium and no. The
following GUI display is obtained.

22
Fig. 2.15. Three triangular membership functions are
chosen for the output variable breaking. The last one has
been activated and renamed as hard.

What is missing from the fuzzy system now is the rule


base. Open View menu and click Edit rules. Then the
following display opens.

23
Fig. 2.16. Rule Editor display. On the right, the input side.
On the left, the output side.

The left-hand side contains the membership functions of


the input, distance. The right-hand side has the
membership functions of the output, brake. If the input
side has several variables, which are connected either by
and or or, the Connection block is in the lower left-hand
corner. In this case we only have one input variable, so
the connective is not used. The weight factor (default
value = 1), indicates the importance of the rule in
question.

The construction of the rule base is the hardest part of the


design task. Here a simple-minded rule base is construc-
ted based on driving experience. Typical rule is

24
If distance is low, then brake is hard.

With mouse choose the membership function low for the


distance and hard for brake. This is done in the figure
above. Then click Add rule. The result is seen below.

Fig. 2.17. Setting up a rule with Rule Editor.

Let us set two other rules, one for medium distance and
the other for long distance. Our simple, rule base is now
complete. Click Close.

25
Fig. 2.18. Complete rule base of three rules. Note the
weighting parameter (1) at the end of each rule, i.e., all rules
have the same weighting.

Now the design of the fuzzy system is complete. The


Toolbox provides two more interesting ways expressing
the rule base.

26
Fig. 2.19. The rule base can be expressed in two other ways
in GUI. Here verbose format is shown.

Check under Options and there choose Format. Under


that you can see that the rules as shown are given verbose.
The other forms are symbolic and indexed. Check in what
form the rule base is given in each case.

Viewing rules gives you the overall picture of the


developed fuzzy system. From the main FIS editor,
choose from View menu View rules.

27
Fig. 2.20. By choosing View the rule base can be viewed
differently.

The display View rules is shown below.

28
Fig. 2.21. The rule base can be displayed graphically. The
red line on the left indicates the value of the input, 15 m.
Similarly the bar on the right hand side, indicates the output
value, 50%.

On the left-hand side you can see the input, distance side
and on the left the output, brake side. There are three rules
and the corresponding triangular membership functions
displayed. In the right-hand side lower corner is the result
of fuzzy reasoning. At this point it is a fuzzy set.
Applying defuzzification method, in the figure center of
gravity has been chosen, a crisp value is obtained.

29
Fig. 2.22. Result of fuzzy reasoning is brake = 50%.

Different input values can be tried by moving the red,


vertical line on the left-hand side (Fig. 2.23).

30
Fig. 2.23. Changing the input value results in different
output values.

Finally, the input-output mapping can be observed by


viewing surface. Choose View menu and under it View
surface. It is clear that our map is nonlinear. This is where
the power of fuzzy systems is strong (Fig. 2.24).

31
Fig. 2.24. The fuzzy system viewed as input-output
mapping.

32
EXAMPLE 2.5: Car Driving - continues
What is missing in Example 2.4?

Distance
d
A B

SPEED!

(relative speed between vehicles A and B).

SOLUTION:

Set up a new rule base with two inputs distance and speed,
one output, braking power.

Here only the main steps are shown.

35
Fig. 2.25. Fuzzy system with two inputs, distance and
velocity, and one output, break.

The second input can be added by opening Edit menu.


Otherwise the steps are as before. Remember to give a
name for the added input. Call it velocity.

Only velocity membership functions are shown because


they are new. Note that the speed range is from -40 to 40
km/h and the range has been divided into three
membership functions: slow, medium, and high speed.

36
Fig. 2.26. Membership functions for the new input, velocity.

Eight rules have been constructed, which are easy to


understand (Fig. 2.27). Of course, the rules are not
unique. Other rules could be used as well. The rule base
must be viewed and tested to see its effectiveness and
how well the system specifications are satisfied.

37
Fig. 2.27. A rule base for Example 2.5.

Viewing the rules is shown in Fig. 2.28.

38
Fig. 2.28. The rule base is viewed graphically. Different
inputs can be chosen to see what the output will be.

Again you can test the system by choosing different values


of inputs. If the result is not satisfactory, then refine the
system. E.g. it seems that the area of short distance and high
speed does not give strong enough braking response.

39
Finally, the surface view of the rules is shown.

Fig. 2.29. The surface view of the constructed rule base.

Note that the right hand-side corner is flat with value zero
over a fairly large area. You can change that by introducing
a new membership function little for breaking power. You
also have to change the rule base. This is done below.

40
2.5. Sugeno-style fuzzy inference
The result of Sugeno reasoning is an exact number.
Consider input-output data given in the table.

x y
- 1.0 1.0
- 0.5 0.25
0 0
0.5 0.25
1.0 1.0
The data is from the function y = x2. The data can be represented using
Mamdani reasoning with e.g. triangular membership functions at the input
and singletons at the output positioned at yi.

Fig. 2.30. Default display of FIS Editor with Mamdani


reasoning.

41
Fig. 2.31. The number of xi points is five. Choose as many
triangular membership functions for input variable.

For each data point generate a triangular membership function, the maximum
of which occurs exactly at a given data point, say mf3 has maximum at x = 0,
which is one of the data points. This is seen in the above figure.

Mamdani reasoning does not support singletons, so let's first choose


triangular membership functions at the output.

42
Fig. 2.32. The number of yi points three. Choose as many
triangular membership functions for output variable.

Then make the base of the triangles narrow, so that they resemble singletons.

Fig. 2.32. Make the basis of output triangular membership


functions as narrow as possible to make them resemble
singletons.

43
Observe again the position of singletons. They have nonzero value exactly at
the output data point. Only three membership functions are needed at the
output. Why?

Next set the rules to be

If x is mfi then y is omfi .

Complete rule base for the example is shown below.

Fig. 2.32. The rule base corresponding to the input-output data


shown in the Table.

We can view the rules by View rules

44
Fig. 2.33. The complete rule base of the example.

The result of our data fitting can be shown below

45
Fig. 2.34. The resulting fuzzy system approximating the given
data.

The fit is exact at the given data points. Overall shape is that of parabola, but
to have a better fit, more data points would be needed.

EXERCISE: Keep the range the same. Add four more data points. Repeat
the procedure and compare the results.

46
The same procedure as above can be produced with Sugeno reasoning.
In Sugeno reasoning the consequence, the output side, is deterministic:

If x is X i then y = yi.
In Mamdani reasoning the determinism is produced with singletons.

Let us repeat the above example with Sugeno reasoning.


In the FIS editor choose New Sugeno FIS.

Fig. 2.35. FIS Editor for Sugeno reasoning.

Then activate the input and name it x. Similarly activate output and name it y.
Next Edit membership functions. Let the input range be [-1 1]. Click Ready so that
your choice is recorded. Determine the input membership functions as
before by Add MF's (5 triangular). Next repeat the same for output. The

47
range is [0 1], which is default value. Then Add MF's. At this point the
following appears.

Fig. 2.36. Choose three, constant output membership functions.

MF type constant corresponds to Mamdani singletons. There are three


different values of output, so choose 3 as Number of MFs. Clicking OK results
in

Fig. 2.37. Membership Function Editor in Sugeno type of fuzzy


system.

48
The values of the constant membership functions are determined by
activating them by clicking with the mouse. Now you change the name and
value of the constant.

Fig. 2.38. Activate membership function mf2.

The final task is to form the rulebase. Choose Edit rules and write them in as
before.

49
Fig. 2.39. The rule base for the example in Sugeno type of fuzzy
system.

The Sugeno FIS system is now complete. Let us view the result. First the
overall rules

50
Fig. 2.40. The complete rule base of the example in the case of
Sugeno type of fuzzy system.

Then the Surface View.

51
Fig. 2.41. The resulting fit of Sugeno type of fuzzy system.

The result is the roughly the same as we obtained before.

Trying gaussmf membership functions results in the following approximating


system.

Fig. 2.42. Fuzzy Sugeno system with gaussian type of


membership functions.

52
More generally the above procedure
would be the following. The input-
output data is given by

x y
x0 y0
x1 y1
M M
xn yn

The rules would be of the form


If x is X i then y = yi.

Then Sugeno type of reasoning with weighted average leads to

m
∑ µ X i ( x) yi
y ( x) = i =1m
∑ µ X i ( x)
i =1

yi = discretization points of membership functions


m = number of rules

REMARK: Weighted average requires that the rule base is complete and
input fuzzy membership functions cover the input space. Otherwise there is a
danger to divide with zero.

53
Sugeno reasoning allows us to use also functions of input x, not only
constants, on the right hand side. The rules would look like

If x is X i then y = fi ( x) .

Function fi can be a different nonlinear mapping for each rule.


x may be a vector and more complicated rule structures can also appear.
Simplest examples of functions fi are straight lines. Let i = 2. Then
y = p1x + r1
y = p2 x + r2
This is supported by Fuzzy Toolbox. More general functions can also be used,
but these have to be set up by yourself.
EXAMPLE: Consider again the example above. Set up a Sugeno system with
five membership functions as before. Use three straight lines at the output:
One with a negative slope, one constant, and one with a positive slope. Start
with very simple ones
1: y = − x
2: y = 0
3: y = x
Define them by Add MF's. Choose linear type.

Fig. 2.43. Choose linear form of membership functions instead


of constant.

54
The two parameters for each straight line can be chosen in Params box. The
slope is first and then the constant.

Fig. 2.44.

The rule base could be e.g.

Fig. 2.45.

55
The overall view of the rules is shown below.

Fig. 2.46.

The Surface View becomes:

56
Fig. 2.47.

The result is smoother than before, but does not agree as well at point x =
0.5, y = 0.25. This would require further fine-tuning of parameters.

Suppose the rules are of the form


If x is X i then y = fi ( x) .
Combining results of all the rules leads to a weighted average

m
∑ µ X i ( x ) fi ( x )
y ( x) = i =1 m
∑ µ X i ( x)
i =1

57
where m = number of rules.

The interpretation is that for a given value of x, the membership functions


smooth (interpolate) the output function fi. This is illustrated below for the
case of straight lines y1, y2, and y3.

y1 y3
y2

µ X1 ( x) µ X 3 ( x)

Fig. 2.48. A function defined by Sugeno model. The


straight lines yi, i = 1,2,3, represent the local models. The
bold line is the final result.

58
The rules can be more general like

If x1 is A1i and … and xn is Ani


then yi = f i ( x1,K, xn )

where the consequences of the fuzzy rules are functions of the input vector
x = [ x1,L, xn ] . A general linear function of Sugeno type at the output is

n
y j = c0j + ∑ ckj xk ,
k =1

where ckj are real-valued parameters and specific to each rule. Since each rule
has a crisp output, the aggregate result is obtained by weighted average.

n i
∑ wi (x) y (x)
y (x) = i =1 ,
n
∑ wi (x)
i =1
where x = [ x1,L, xn ] and wi depends on the applied T-norm for logical and.
If product is chosen and the number of rule is m, then

m
wi = ∏ µ Ai ( x), i = 1,L, n .
i =1

REMARK: Sugeno systems using constants or linear functions in the


consequence are clearly parameterized maps. Therefore it is possible to use
optimization techniques to find best parameters to fit data instead of trying to
do it heuristically. Depending on the choice of T-norm and defuzzification,
the expression above may change, but will always have similar structure.

Basis Functions and curve fitting

Mendel-Wang's Mamdani type, fuzzy logic system is given by

59
j ⎛⎜ ⎞
n m
∑ w ⎜ ∏ µ j ( xi ) ⎟⎟
Xi
j =1 ⎝ i =1 ⎠
y ( x) = ,
n ⎛m ⎞
∑ ⎜⎜ ∏ µ X j ( xi ) ⎟⎟
j =1⎝ i =1 i ⎠

where w j is the place of the output singleton. The membership


function µ j ( xi ) corresponds to the input xi of the rule j. The and-
Xi
connective in the premise are realized with product and defuzzification with
Center of Gravity method. The rules are of Mamdani type. Comparing the
equation with the Sugeno expression, it is easy to see that choosing y j to be
constant and w j = y j , the result is the same.

It is useful to define a fuzzy basis function

m
∏ µ X j ( xi )
b j ( x) = i =1 i
n ⎛m ⎞
∑ ⎜⎜ ∏ µ X j ( xi ) ⎟⎟
j =1⎝ i =1 i ⎠

where the denominator normalizes the product of membership functions so


that the sum of basis functions yields one at each point. Functions bj are
called basis functions, although they are not always orthogonal.

The fuzzy system can now be written in a simple way

n
y (x) = ∑ wibi (x) .
j =1

Although the above does not look like a fuzzy system, it can be interpreted as
such, because it is formed using membership functions, T-norms and T-
conorms. This form further implies the use of optimization techniques in
determining the parameters in a fuzzy system in the best way.

60
61
Curve fitting
Suppose input-output data
x y
- 1.0 − 1.2
- 0.5 − 0.3
0 0 .2
0.5 0.4
1.0 1.2
is given. Assume a linear model y = ax + b . Find the best a and b to fit the
data.

Least squares fit:

Form a cost function

n
J (a, b) = ∑ ( yi − axi − b )2
i =1

This represents the cumulative error. Minimize J(a,b) with respect to (a,b).

Plot the data


x=[-1 -.5 0 0.5 1]; y=[-1.2 -0.3 0.2 0.4 1.2];
plot(x,y); grid

62
Fig. 2.49. Plotting data.

Many numerical optimization schemes can be applied to solve the


minimization problem. These include gradient (steepest descent), Gauss-
Newton, Levenberg-Marquardt. These are included in the MATLAB
Optimization Toolbox. They can be studied by typing optdemo.
One special one is ANFIS which is included in the Fuzzy Toolbox. ANFIS is
used later on fuzzy systems.

Apply here LSQNONLIN in MATLAB

help LSQNONLIN
LSQNONLIN Solves non-linear least squares problems.
LSQNONLIN solves problems of the form:

63
min sum {FUN(X).^2} where X and the values returned by FUN can be
x vectors or matrices.

X=LSQNONLIN(FUN,X0) starts at the matrix X0 and finds a minimum X


to
the sum of squares of the functions in FUN. FUN accepts input X and returns
a vector (or matrix) of function values F evaluated at X. NOTE: FUN should
return FUN(X) and not the sum-of-squares
sum(FUN(X).^2)). (FUN(X) is summed and squared implicitly in the
algorithm.)

Examples
FUN can be specified using @:
x = lsqnonlin(@myfun,[2 3 4])
where MYFUN is a MATLAB function such as:
function F = myfun(x)
F = sin(x);

FUN can also be an inline object:


fun = inline('sin(3*x)')
x = lsqnonlin(fun,[1 4]);.

Apply to the current problem

lsqnonlin('([-1.2 -.3 .2 .4 1.2] -x(1)*[-1 -.5 0 .5 1]-x(2)*ones(1,5))',[0 0])


ans = 1.1000 0.0600

Plotting both the data and the fitted straight line the figure below is obtained.
yy=1.1*x+0.06
plot(x,yy,'or')
hold % Current plot held
plot(x,y)
grid

64
Fig. 2.50. Result of linear curve fitting.

One could use also polynomial fit. Then the command is polyfit. This
command fits a polynomial of given degree to the data:

POLYFIT Fit polynomial to data.


POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) of degree N that fits the data,
P(X(I))~=Y(I), in a least-squares sense.
[P,S] = POLYFIT(X,Y,N) returns the polynomial coefficients P and a structure S for use with
POLYVAL to obtain error estimates on
predictions. If the errors in the data, Y, are independent normal with constant variance,
POLYVAL will produce error bounds which
contain at least 50% of the predictions.
The structure S contains the Cholesky factor of the Vandermonde matrix (R), the degrees of
freedom (df), and the norm of the residuals (normr) as fields.

If a third order polynomial is used, the command works as follows:

65
[p,s]=polyfit(x,y,3)
p = 0.6667 -0.1429 0.5333 0.1314
s = R: [4x4 double] df: 1 normr: 0.0956

Here p gives the coefficients of the polynomial in descending order (highest


power first). To compare the answer with the least squares fit, the polynomial
must be evaluated at the points x. For that there is a convenient command
polyval(p,x). Apply that

y1=polyval(p,x);

and plot all the data and the least square straight line and third order
polynomial to the same figure.
xx=-1:0.01:1;
y1=polyval(p,xx);
yy=1.1*xx+0.06;
plot(x,y);hold; plot(xx,y1,'xr',xx,yy,'obl'); grid
This yields

66
Fig. 2.51. Curve fitting on given data (blue), straight line (black) and third
order polynomial fit (red).

The joy of MATLAB commands in curve fitting is not complete, if spline


functions and their fit are not mentioned. Splines offer many times the best
fits. Study MATLAB command spline.

67

You might also like