U 3 M-file Programming NIT

advertisement

Unit 3. M-file Programming

U NIT 3

M-file Programming

1.

  Introduction ............................................................................................................. 2  

1.1

  M-file editor ........................................................................................................ 2  

1.2

  M-file debugging ................................................................................................ 4  

2.

  Scripts and functions ............................................................................................... 9  

2.1

  Script programming ........................................................................................... 9  

2.2

  Function programming ..................................................................................... 11  

3.

  Programming language ......................................................................................... 19  

3.1

  Input and output commands ............................................................................. 19  

3.2

  Indexing ............................................................................................................ 21  

3.3

  Flow control ..................................................................................................... 25  

3.4

  Conditional structures ...................................................................................... 28  

4.

  Functions use other functions as input arguments ............................................. 29  

4.1

  Solving equations ............................................................................................. 29  

4.2

  Solving differential equations ........................................................................... 31  

4.3

  Optimization ..................................................................................................... 32  

4.4

  Timers ............................................................................................................... 35  

4.5

  Integration and derivation ................................................................................ 36  

4.6

  Interpolation and regression. Polynomial fitting of curves ............................ 40  

5.

  Signal Processing ................................................................................................... 45  

5.1

  Audio processing .............................................................................................. 45  

5.2

  Fast Fourier Transform (FFT) ......................................................................... 46  

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 1

Unit 3. M-file Programming

1. Introduction

The MATLAB powerfulness is due to the fact that it is possible to run a large number of commands from a text file. These files are known as M-files because their names are of the form filename.m

. M-files can be functions that accept input arguments and produce an output, or they can be scripts that execute a series of MATLAB statements.

Commercial toolboxes and other free access toolboxes contain M-files. MATLAB users can edit and modify the M-files of the toolboxes and they can create their own Mfiles as well.

To list the toolboxes installed in your computer, together with their versions and date, type >>ver in the command window.

To list the contents of a particular toolbox, you can simply enter >>help toolbox_name . For example, >>help matlab\general or >>help control .

M-files are text files. Therefore any text editor (such as the Windows Notepad) can be used to edit them. However it is advisable to use the M-files editor available in the

MATLAB itself since it has debugging utilities and makes the programming easier due to the color code used with the reserved words.

Click on the icon to open the M-file editor ( in v8). You can also double-click on any already existing M-file or use the menu bar options: File

New

M file .

Fig. 1. M-file editor in MATLAB v7.11

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 2

Unit 3. M-file Programming

Fig. 2. M-file editor in MATLAB v8

Work folder: By default, M-files created by the user are stored in the <work> directory. Apart from the M-file filename.m

, the M-file editor also produces an autosave file of name filename.asv

.

To see the code of filename.m

without having to open the M-file editor simply type

>>type filename in the command window. For instance, >>type roots . Note: built-in functions are not M-files but there exist M-files with the same name containing the help comments. For instance, try >>type who and >>type who.m

.

Menu bar options: The menu bar and the toolbar present many utilities. Look to the available options and try to deduce what they do.

Some interesting options are:

File

Preferences… (to change the general parameters regarding colour, text fonts, etc.)

Cell (if you want to execute only a part of the code)

Tools

Check Code with M-Lint (to get suggestions about correcting and improving your code)

Debug

Run (to save and run the M-file. This option is equivalent to click on the icon)

In the v8 the Preferences options can be found in Home>Environment (see Fig. 3).

Fig. 3. Environment in v8

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 3

Unit 3. M-file Programming

Color hints: In versions 7 and 8, colors in the frame of the M-file editor give hints about your code. If there are no errors a green square appears on the frame. If there are errors a red square appears instead. If there are warnings or suggestions (such as the semicolon in line 1 in the example below), the square that appears in the frame is orange.

Fig. 4. M-file editor in MATLAB v7

Breakpoints: It is possible to insert breakpoints. Click on the icons to insert or to clear breakpoints in the selected lines or use the Debug options in the menu bar.

To run the file click on or . Use the remaining icons file step-to-step, to clear all breakpoints, etc.

to run the

While the breakpoint mode is used, the prompt in MATLAB is k>> . Also, the current line is indicated by means a green arrow inside the M-file:

Breakpoints are of several types:

Standard: They are the red ones. When the running code finds a standard breakpoint, the running is paused.

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 4

Unit 3. M-file Programming

Conditional: They are the yellow ones. To insert a conditional breakpoint, click on the selected line and select

Debug

 Set/Modify Conditional

Breakpoint… A dialog box is opened to introduce the condition that will pause the code execution:

 Error: They also are red. To insert an error breakpoint click on the selected line and select Debug

Stop if Errors/Warnings . A dialog box is opened to introduce the error type, warning type or value (

NaN

,

Inf

) that will stop the code execution:

M-Lint Code Check: In v7, to activate it go to Tools

Save and Check Code with M-Lint . In v8 go to .

The example in Fig. 5 illustrates the code checking. The report indicates the following issues:

It says that functions meshdom and fmins do not exist anymore and it suggests using meshgrid and fminsearch instead.

It indicates which lines do not have semicolon.

It warns us of the existence of variables that have not been used ( hdb ).

Finally, it says that we cannot declare a function in the middle of a script file

(functions can only be declared inside other functions). Therefore it is necessary

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 5

Unit 3. M-file Programming to convert the script ft3d to a function. To do so, the first line in the file must be function ht3d .

Fig. 5. Code analysis in MATLAB v7

Cell mode: To activate cell mode select Cell

Enable Cell Mode . The following bar corresponds to the cell mode:

The cell mode is useful to execute selected parts of the code or to change parameters without having to save the M-file.

To specify which lines form a cell, type %% before and after the selected lines (or use the options in the menu bar). To run a cell, select it and click on .

To change a parameter value and immediately see the effect, select the parameter and use the + and – signs in the button so-called “rapid code iteration”).

. The cell will run automatically (it is the

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 6

Unit 3. M-file Programming

Profiler: Select the option Tools

Open Profiler and, once inside, click on the

Start Profiling button.

Fig. 6. Profiler in v7

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 7

Unit 3. M-file Programming

The profiler tool allows seeing the time used by every line of the M-file code and how many times each command is called. This tool is useful to eliminate redundancies and to write more efficient files.

Publishing: Click on to create an html document with the script commands as well as the script results. For instance:

Fig. 7. Publishing in v7

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 8

Unit 3. M-file Programming

2. Scripts and functions

There are two types of M-files: scripts and functions.

Scripts:

 They have not input or output arguments.

To execute a script file you can simply type its name (with no extension) in the command window.

 All variables created by the script are stored in the workspace.

Functions

Function files may have input and/or output arguments.

To execute a function file you have to specify the value of its input arguments, if there are any.

Internal variables created inside the function are not stored in the workspace

(only variables declared as output arguments or declared as global variables are stored in the workspace).

A script is a text file, of extension *.m

, that contains a sequence of MATLAB commands (simple commands, functions and invocations to other scripts), written as if they were called from the command window (but without the prompt >>). programming

Next figure shows the script called curva.m

.

Fig. 8. Example of a script type M-file

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 9

Its execution results in the two following figures:

Unit 3. M-file Programming

Scripts use the variables stored in the MATLAB workspace, and the variables created by the script are stored in the workspace as well.

To execute a script it is enough to type its name (with no extension) in the command window. Also in the M-file editor you can select the menu option Debug

Run

(F3) or click in the icon (or in the icon, depending on the version).

Inserting comments: To insert a text comment, simply type the % symbol at the beginning of the comment (it is not necessary to close the comment with another %).

Notice that green is the default color for comments.

Cleansing commands: Although not mandatory it is recommended to begin a script file with some cleansing instructions such as hold off , clear all , axis , subplot , close all , close all hidden , clc …

Other useful commands:

 pause : it pauses the running script until the user press any key. It is also possible to stop the script a particular time, for instance, pause(2) .

 disp : displays text in the command window. For instance, the commands

N=15.6; disp([ 'And the N value is... ' ,num2str(N), '!!' ]) give the following result:

And the N value is... 15.6!!

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 10

Unit 3. M-file Programming

( num2str means number-to-string. Notice that the input argument in disp is a character string). The following syntax is also valid (now, the input argument of disp is a cell of strings. The cell is indicated by means the { } symbol):

>> disp({ 'hi' ; 'bye' })

'hi'

'bye'

 figure : Before a plot command, it is a good idea to include a command figure , figure(1) , figure(2) ,… This way, when the script is running, figure windows will be directly opened in the front of the screen.

 echo on/off :

This command is used in many demos in order to present, during the running of the script, the commands that contain the script.

 tic and toc , also etime : They show the elapsed time spent by a command or a group of commands.

...

: if a command is too long you can put the three points and continue in the next line (this is useful when entering large matrix data).

Scripts execute a series of MATLAB statements. Functions also execute a series of

MATLAB statements but they accept input arguments and may produce one or several outputs. Functions are preferred to scripts in situations where a same code has to be used several times, for different parameters which can be introduced in an external way.

Next figure shows the suma_resta function file.

Fig. 9.

Example of a function type M-file.

In the first line we declare the function name along with the list of input and output arguments.

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 11

Unit 3. M-file Programming

It is possible to declare several functions inside the same file. However the file name must be the primary function name.

Running a function: Next figure shows the use of the function:

Fig. 10.

Help and run of suma_resta function in the command window.

Structure: A function M-file consists of three parts:

Header: Here we declare the function: function [sine,cosine,tangent]=function_name(ang)

 Help comments: They are optional. Help comments is what appear in the command window when we type >>help function_name

% FUNCTION_NAME computes sine, cosine and tangent of

% the angle stored in variable 'ang'

If a blank line is inserted in between the help comments lines, help comments will be considered only the ones before the blank line.

Commands: sine=sin(ang); cosine=cos(ang); tangent=tan(ang);

To call a function one must use the following syntax:

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 12

Unit 3. M-file Programming

»[output_arguments] = function_name (input_arguments)

Notice that:

Output arguments are inside brackets

Input arguments are inside parentheses

It is not necessary to finish the file with the instruction end . However, if you close a function with an end , then all functions inside the same M-file must be closed with an end .

The name of the file must coincide with the name of the main function

The comments are preceded by the symbol % (it is not necessary put another % to close the comment)

The helps of the toolboxes’ functions indicate the function aim and its syntax.

Although in these helps the name of the function always appears in uppercase, the functions in MATLAB are usually called in lowercase.

Global variables: M-file scripts do not need global variables since they operate directly on the data in the workspace.

On the contrary, for M-file functions, internal variables (provided they are not output arguments for the function) are by default local to the function and they are not passed to the workspace. To overcome this situation, we can define global variables (outside and inside the function).

>>global SAMPLING_PERIOD

Although not mandatory, it is usual to name such variables with uppercase long names.

Number of input and output arguments. Optional parameters: Functions nargin

(number of input arguments) and nargout (number of output arguments) allow different usages for a same function.

Consider for example the function step (from the Control Systems Toolbox ): with no output arguments, this function plots the step response of a system. When called with an output argument y , it stores the step response samples in variable y and does not plot them.

Example 3. Using nargin and nargout function [numz,denz]=discret(nums,dens,Type)

%Syntax: [numz,denz]=discret(nums,dens,Type)

% Type can be 'Tustin', 'BwdRec' or 'FwdRec' if nargin==0

disp( 'Enter the system, now!!!' ) else

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 13

Unit 3. M-file Programming if Type=='Tustin'

statements to perform the following discretization s

2

T end z z

1

1 if Type=='BwdRec'

statements to perform the following discretization s

 z

1

Tz end if Type=='FwdRec'

statements to perform the following discretization s

 z

1

T end end if nargout==0

disp( 'buf!' ) end

>> help discret

Syntax: [numz,denz]=discret(nums,dens,Type)

Type can be 'Tustin', 'BwdRec' or 'FwdRec'

>> [a,b]=discret

Enter the system, now!!!

Warning: One or more output arguments not assigned during call to 'discret'.

>> discret(2,3,'Tustin') buf!

>>

Other interesting functions are varargin (variable number of input arguments) and varargout (variable number of output arguments); and nargchk (check number of input argument s ) and nargoutchk (check number of output arguments).

4. and

A function can be called with a varying number of input arguments if we declare it as follows: function y=func1(x,varargin)

%with, the following statements, for instance figure,plot(x,varargin{:})

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 14

Unit 3. M-file Programming varargin, x1=varargin{1}, x2=varargin{2}, x3=varargin{3}, x4=varargin{4},

Thus, we can use a variable number of input arguments after x. If we call the function as below we are using 4 additional input arguments among x:

>>func1(sin(0:.1:2*pi), 'color' ,[1 0 0], 'linestyle' , ':' )

The inner variable “varargin” is a 4x1 cell array and its components are, respectively, varargin (1) = 'color', varargin (2) = [1 0 0],... varargin =

'color' [1x3 double] 'linestyle' ':' x1 = color x2 =

1 0 0 x3 = linestyle x4 =

:

1

0.8

0.6

0.4

0.2

0

-0.2

-0.4

-0.6

-0.8

-1

0 10 20 30 40 50 60 70

If we want a function which generates a variable number of output arguments we can use varargout : function [varargout]=func2(x,varargin)

Auxiliary and nested functions: A function type M-file can include several functions.

If these functions are auxiliary functions used by the main function, they are all declared at the end of the file and it is not necessary to finish none of them with the word end .

However, if a function is finished with an end , then all functions must be finished with an end word. In next example pmat2f1 and pmat2f1n are auxiliary functions for the main function ft3d .

To access the auxiliary functions use the symbol >.

>> help ft3d>pmat2f1

|H(s)| en dB

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 15

Unit 3. M-file Programming function ft3d num=(196/9)*[1 0.2 9];den=conv([1 0.0002 49],[1 0.4 4]); x=-0.5:0.1:4;y=-10:0.1:10;[xx,yy]=meshgrid(x,y); z=20*log10(abs(polyval(num,xx+j*yy)./polyval(den,xx+j*yy))); mesh(x,y,z),title( '|H(s)| en dB' ),xlabel( 'sigma' ),ylabel( 'omega' ), minimo=fminsearch(@pmat2f1,[-0.1,2]) h_en_min=pmat2f1(minimo),pause maximo1=fminsearch(@pmat2f1n,[-0.2,3]) h_en_max_1=pmat2f1(maximo1),pause maximo2=fminsearch(@pmat2f1n,[-0.002,9]) h_en_max_2=pmat2f1(maximo2),pause function [hdb]=pmat2f1(in)

% |H(s)| en dB s=in(1); w=in(2); num=(196/9)*[1 0.2 9];den=conv([1 0.0002 49],[1 0.4 4]); hdb=20*log10(abs(polyval(num,s+j*w)./polyval(den,s+j*w))); function [hdb]=pmat2f1n(in)

% |1/H(s)| en dB s=in(1); w=in(2); num=(196/9)*[1 0.2 9];den=conv([1 0.0002 49],[1 0.4 4]); hdb=-20*log10(abs(polyval(num,s+j*w)./polyval(den,s+j*w)));

When we run the function, the result is:

|H(s)| en dB

100

50

0

-50

-100

10

5 4

0

3

2

-5

1

0

-10 -1

 minimo =

-0.1000 2.9983 h_en_min =

-317.0491

Exiting: Maximum number of function evaluations has been exceeded

- increase MaxFunEvals option.

Current function value: -309.711370 maximo1 =

-0.0001 7.0000 h_en_max_1 =

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 16

Unit 3. M-file Programming

309.7114 maximo2 =

-0.0001 7.0000 h_en_max_2 =

306.8104

In the case of nested functions, these can be declared everywhere inside the function file but it is mandatory to close them with an end . The main function must be closed with an end too. function main

… function nested

… end

… end

Local functions (inline functions): You can create local functions in the command window, in scripts and in functions. The advantage is that there is no need to store them in a separate file, but they have limitations (they cannot be nested and they have only one output argument).

Example 6. Local functions ( inline )

If we want to compute the area of a standard Gaussian bell between ±

, ±2

, and ±3

, we can do the following: f=inline( 'normpdf(x,0,1)' , 'x' ) %f is the normal pdf with sigma=1 f =

Inline function:

f(x) = normpdf(x,0,1) a=quad(f,-1,1) a =

0.6827 a=quad(f,-2,2) a =

0.9545 a=quad(f,-3,3) a =

0.9973

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 17

Unit 3. M-file Programming

Local functions can be also created by using the symbol @ instead of the inline function. For instance, consider the following function

>> f = @(x)x.^2-3 f =

@(x)x.^2-3

>> f(2) ans =

1

We can obtain its zero by means of fzero . As first input argument, we can refer to the existing function f or directly introduce its expression as a local function:

>> fzero(@(x)x.^2-3,0.2) ans =

-1.7321

>> fzero(f,0.2) ans =

-1.7321

Finally, inline functions can also present several input arguments:

>> g=@(x,y)1./(1+x.^2+y.^2) g =

@(x,y)1./(1+x.^2+y.^2)

>> [x,y]=meshgrid(-3:.1:3); surf(x,y,g(x,y));

1

0.8

0.6

0.4

0.2

0

4

2 4

2

0

0

-2

-2

-4 -4

Private functions: These are functions that are within the <private> directories.

They can only be seen and called by functions and scripts that are in the directory immediately above the <private> directory. Since they are avalaible only for a few functions, their name can be the same as other standard functions of MATLAB, for example, bode.m

. When from the directory immediately above to

<private>

we call the bode function, then bode.m

of

<private>

is executed instead of standard bode.m

.

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 18

Unit 3. M-file Programming

3. Programming language

3.1 Input and output commands

Input and output commands allow the communication with the user. Look the help of the following commands and try the different available options.

Input from keyboard: Use the function input

>> x=input('Enter a number: ')

Enter a number: 7 x =

7

>> y=input('Enter a text:', 's')

Enter a text: hello y = hello

>>

(Notice that in the workspace, y is a char array ( string ) of dimension

1

5

and 8 bytes. This information can be accessed directly from the workspace or from the command window by typing >>whos )

Input from mouse: It is possible to open a dialog box with questdlg , respuesta=questdlg('¿Y tu de qué vas?','Pregunta',...

'De Barrabás','Que mola más','¿gñ?','¿gñ?')

(The default answer button is the last input argument, see the function help for more details)

Output to screen: Functions disp and sprintf display text and results in the command window. disp displays character string data sprintf displays data in a chosen format

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 19

Unit 3. M-file Programming disp can be used along with the following format conversion commands:

 num2str ( number-to-string )

 int2str ( integer-to-string )

 mat2str ( matrix-to-string )

 poly2str ( polynomial-to-string )

 lab2str ( label-to-string )

 rats ( rational approximation )

>> disp(['polynomial=' poly2str([3 4 5],'x')]) polynomial= 3 x^2 + 4 x + 5

>> mat2str(ones(2)) ans =

[1 1;1 1]

>> rats(3.4) ans =

17/5 sprintf has many options: \n , \r , \t , \b , \f , \\ , %% ,... and formats: %d , %i , %o , %u ,

%x , %X , %f , %e , %E , %g , %G , %c , %s

>> sprintf('%0.2f',(1+sqrt(5))/2) ans =

1.62

>> sprintf('Result is %0.5f',(1+sqrt(5))/2) ans =

Result is 1.61803

>>

It is recommended to use the help command for the previous functions and explore the different options.

Other formats: Other useful possibilities for data labeling are:

>> title('\omega_n')

>> xlabel('\Theta_n')

>> text(0.2,0.2,'\it \phi^n')

In the example, the text command writes

 n

in the (0.2,0.2) coordinates of the last figure selected. Type >>help LaTex for more information.

Wait bars: For instance: h=waitbar(0,'¡Espérate un poco, anda!'); for i=1:5, pause(1),waitbar(i/5,h); end , pause(1),close(h)

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 20

Unit 3. M-file Programming

Error messages: Error messages are produce by means the error function. See next example. messages

Consider the function called mult2.m

If we call function mult2 without specifying any input argument, the result is:

>> z=mult2

??? Error using ==> mult2

Esta funcion necesita un argumento de entrada

>>

Note: nargin (number of input arguments) gives the number of input arguments the function has been called.

3.2 Indexing

Indexes: First index in MATLAB is “1”. x = [0.3 0.2 0.5 0.1 0.6 0.4 0.4];

Index: 1 2 3 4 5 6 7

Use parentheses, ( ) , to access the elements of vectors and matrices.

Check that if you type >>x(0) , MATLAB gives the following error message:

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 21

Unit 3. M-file Programming

>> x(0)

??? Subscript indices must either be real positive integers or logicals.

>> x(5) ans =

0.6

Function “find”: Use this function to find vector elements that satisfy a given Boolean condition. For instance,

>> x=[0.3 0.2 0.5 0.1 0.6 0.4 0.4];

>> i=find(x==0.9) i =

[]

>> i=find(x>0.4) i =

3 5

Note: This function also works with matrices: [i,j]=find(A~=0) .

Other useful functions are sort , rot90 , flipud , and fliplr ( fliplr(x) is equivalent to rot90(x,2) ).

Multidimensional arrays. They are an extension of matrices. A matrix is a two dimension array consisting of rows and columns. A three dimension array consists of rows, columns and pages. Dimensions equal or greater than four do not have a particular name. Next, we illustrate a three dimension array consisting of 2 rows, 2 columns and 3 pages:

>> A=[1 2;3 4];

>> A(:,:,2)=eye(2);

>> A(:,:,3)=eye(2)*2;

>> A

A(:,:,1) =

1 2

3 4

A(:,:,2) =

1 0

0 1

A(:,:,3) =

2 0

0 2

Function “squeeze”: This function removes singleton dimensions in multidimensional arrays. To illustrate the usage, consider the following Control Systems Toolbox example: When the function bode is applied to transfer function ( tf ) objects, the results mag and phase are three dimension arrays. If we want to extract only the magnitude values we can use the function squeeze to eliminate the singleton dimensions:

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 22

Unit 3. M-file Programming

>> G=tf(1,[1 1]);

>> [mag,phase]=bode(G);

>> size(mag) ans =

1 1 45

>> mag=squeeze(mag);

>> size(mag) ans =

45 1

“Cell” and “struct” data types: Sometimes we want to store data of different types and/or dimensions in an only one variable. In this case it is useful to consider cell

and struct data types:

Example with cell :

>> cosas_varias=cell(1,3)

%we create the cell variable of dimension 1 x 3 cosas_varias =

[] [] []

>> cosas_varias{1}=1

%to access any cell element use the symbol { } cosas_varias =

[1] [] []

>> cosas_varias{2}=eye(2) cosas_varias =

[1] [2x2 double] []

>> cosas_varias{3}=eye(3) cosas_varias =

[1] [2x2 double] [3x3 double]

>> cosas_varias{3} ans =

1 0 0

0 1 0

0 0 1

Example with struct :

>> mis_cosillas.cosa1='hola' mis_cosillas =

cosa1: 'hola'

>> mis_cosillas.cosa2=1:5 mis_cosillas =

cosa1: 'hola'

cosa2: [1 2 3 4 5]

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 23

Unit 3. M-file Programming

>> mis_cosillas.cosa3=zeros(3) mis_cosillas =

cosa1: 'hola'

cosa2: [1 2 3 4 5]

cosa3: [3x3 double]

>> mis_cosillas.mas_cosas.cosa4=8.2 mis_cosillas =

cosa1: 'hola'

cosa2: [1 2 3 4 5]

cosa3: [3x3 double]

mas_cosas: [1x1 struct]

Date format, “datestr” and “datenum”: MATLAB handles dates in a numeric format. Date 1 corresponds to the year 0, January 1 st

.

The function datestr shows the date in a char array format:

>> datestr(1) ans =

01-Jan-0000

The function datenum convert a char array date in a number date. The second input argument specifies the date format (for example “dd/mm/yy” or “mm/dd/yy”).

>> datenum('1/2/07') ans =

733044

>> datestr(ans) ans =

02-Jan-2007

>> datenum('1/2/07','dd/mm/yy') ans =

733074

>> datestr(ans) ans =

01-Feb-2007

Other useful functions are now and today .

>> now ans =

7.3552e+05

>> datestr(ans) ans =

08-Oct-2013 16:51:55

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 24

Unit 3. M-file Programming

There are many flow control statements in MATLAB: for…end: It executes a group of statements a fixed number of times. The syntax is the following:

>> for index=start:increment:end, statements, end

>> for i=1:3 disp( 'bah!' ) end bah! bah! bah!

>>

The default increment is 1 . You can specify any increment, including negative ones.

For example, i=0:0.1:7 or m=-5:-0.1:0 . For positive indexes, execution ends when the value of the index exceeds the end value. It is possible to nest multiple loops.

A useful function when programming loops is the command length , for example: i=1:length(x) .

Example 8. FOR loop. Trajectories in a state plane

The following system is described by means its state equations: y

0

3

1

4

 x

2 1

 x

0

 u



0

1

 u

If we want to plot the response to different values for the initial conditions x (0), we can use a for…end loop for each state variable. a=[0 1;-3 -4];b=[0;1];c=[2 1];d=0;

G=ss(a,b,c,d); for x1=-1:0.25:1 for x2=-1:0.25:1

[y,t,x]=initial(G,[x1;x2]);

plot(x(:,1),x(:,2)),hold on end end axis([-1 1 -1 1]), title( 'State Plane' ) xlabel( 'x_1' ),ylabel( 'x_2' )

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 25

Unit 3. M-file Programming

State Plane

1

0.8

0.6

0.4

0.2

0

-0.2

-0.4

-0.6

-0.8

-1

-1 -0.8

-0.6

-0.4

-0.2

0 x

1

0.2

0.4

0.6

0.8

1

Before running a for loop is recommended to initialize variables with the zeros function to optimize the performance (if not, MATLAB dynamically allocate memory for the variables of the loop, thereby incurring overhead). while…end: It executes a group of statements a definite number of times, based on some logical conditions. The syntax is the following:

>> while (logical_expression), statements, end

>> i=3;

>> while gt(i,1) i=i-1; disp( 'burp' ) end burp burp

>>

Relational operators: equal to ( == ), less than ( <) , greater than ( >) , greater than or equal to ( >=) , less than or equal to ( <=) , not equal to ( ~= ). There exist the corresponding functions: eq ( equal ), ne ( not equal ), ge ( greater than or equal ), lt

( less than ),...

It is usual to specify logical expressions between parentheses, (x==2)

To get more information, you can see the help for the dot “.”, that is: >>help .

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 26

Unit 3. M-file Programming

We want to evaluate the following expression [mag,05] f ( x )

 e

0 x / 2 a

 x

 b otherwise for a =-1 and b =2:

>> a=-1;b=2;

>> x=-3:3;

>> g=exp(x/2).*(a<=x & x<b) g =

0 0 0.6065 1.0000 1.6487 0 0

The Boolean condition is:

>> (a<=x & x<b) ans =

0 0 1 1 1 0 0

Logical operators: and (

&

), or (

|

), not (

~

), xor ( xor(x,y) )

Other useful functions: isempty (is empty?), ischar , isnan , isinf , isfinite , isglobal , strcmp (string comparison)… Value 1 means TRUE and value 0 means

FALSE.

>> x=[] x =

[]

>> isempty(x) ans =

1

>>

>> y='hello' y = hello

>> strcmp(x,'bye') ans =

0

Other useful commands:

To abort the execution: break exits the loop. Kills the script execution return returns to keyboard or to the function that has called the loop

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 27

To round numbers: ceil ceil(1.4)=2 ceil(-1.4)=-1

Unit 3. M-file Programming if_elseif_else_end: This control statement executes a group of statements based on some logical conditions. The syntax is: if (logical_expression) statements elseif (logical_expression) statements else statements end switch_case_otherwise_end: This statement executes different groups of statements depending on the value of some logical condition.

For instance, in the next example the variable hello can have the following values:

‘yes’ , ‘no’ or ‘maybe’ : switch hello case {‘yes’,’maybe’} statements case ‘no’ statements otherwise statements end

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 28

Unit 3. M-file Programming

4. Functions use other functions as input arguments

Function handle: Several functions have input arguments that are other functions.

Such an input argument is called “function handle” and it is composed by the symbol

@ followed by the function name,

@function_name

. In the following sections, several application examples are presented.

Main functions are fsolve

and fzero

. Usually, functions that begin with “f” ( fzero

, fsolve

, fminsearch

, feval

,…) are functions which input arguments are other functions. To list the default parameters of the optimization subroutines, type

>>help foptions

.

Example: We want to solve the following equation: tg

1



2



 e

.

First at all, edit an M-file equation.m

containing the following function function y=equation(beta) y=atan(2/beta)-exp(beta);

Input argument is

and output argument is y

 tg

1



2



 e

.

Using fzero: fzero

finds the zero in nonlinear functions of one variable. First input argument is the equation to be solved. The second input argument is the initial guess about where the zero is (this guess can be a scalar value or an interval). If the initial value is too far from the solution fzero

would fail and give no solution at all.

>> format long

>> beta=fzero(@equation,1) beta =

0.33865534225523

>> beta=fzero(@equation,10)

Exiting fzero: aborting search for an interval containing a sign change

because NaN or Inf function value encountered during search.

(Function value at 829.2 is -Inf.)

Check function or try again with a different starting value. beta =

NaN

Using fsolve: fsolve

solves nonlinear multivariable equation systems. Its syntax is the same than fzero

.

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 29

Unit 3. M-file Programming

>> beta=fsolve(@equation,1)

Optimization terminated: first-order optimality is less than options.TolFun. beta =

0.33865534237264

>> beta=fsolve(@equation,10)

Optimization terminated: first-order optimality is less than options.TolFun. beta =

0.33865534667084

Notice that the result is slightly different since the solving method is different too

( fsolve

belongs to the Optimization Toolbox whereas fzero

is part of the MATLAB kernel)

>> which fsolve

C:\Archivos de programa\MATLAB704\toolbox\optim\fsolve.m

>> which fzero

C:\Archivos de programa\MATLAB704\toolbox\matlab\funfun\fzero.m

More options: The third input argument is optional and gives information about the iterations and numerical methods. Type

>>help optimset

for more information.

>> options=optimset('Display','iter');

>> beta=fzero(@equation,[0.3 0.4],options)

Func-count x f(x) Procedure

2 0.3 0.0720476 initial

3 0.337826 0.00156645 interpolation

4 0.338656 -5.18785e-007 interpolation

5 0.338655 1.50686e-010 interpolation

6 0.338655 0 interpolation

Zero found in the interval [0.3, 0.4] beta =

0.33865534225523

>> beta=fsolve(@equation,0.3,options)

Norm of First-order Trust-region

Iteration Func-count f(x) step optimality radius

0 2 0.00519085 0.132 1

1 4 9.85129e-007 0.0391806 0.00188 1

2 6 3.33215e-014 0.000525202 3.45e-007 1

Optimization terminated: first-order optimality is less than options.TolFun. beta =

0.33865543888303

Anonymous functions: If the equation to be solved is simple or simply we do not want to create an M-file every time we want to solve a function, we can use the so-called anonymous functions. An anonymous function is defined directly in the function handle. For instance:

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 30

Unit 3. M-file Programming

>> func_anon=@(beta)(atan(2/beta)-exp(beta));

>> x=fsolve(func_anon,1)

Optimization terminated: first-order optimality is less than options.TolFun. x =

0.3387

Syntax for anonymous functions is:

@(arguments)(expression)

It is also possible to use parameters: ct=2;func_anon=@(beta)(atan(ct/beta)-exp(beta));

4.2 Solving differential equations

Main functions for solving ordinary differential equations (ODE) are: ode23 ode45

:

: for 2 nd

or 3 rd

order ODEs for 4 th

or 5 th

order ODEs

Syntax is:

>> [t,y]=ode23(@function_name,[Tini Tfin],init_cond);

The M-file function_name.m

must contain the state equations corresponding to the differential equation to be solved. See the next example:

Simple pendulum dynamics: The dynamics of the pendulum of the figure are described by the following equation:

         sin

   

0 .

 L m

 mg

State equations: Firstly, we have to translate the ODE (of n -th order) to ( n ) state space equations (which are differential equations of first order).

will be denoted x

1

: x

1

will be denoted x

2

(note that x

1

 x

2

    

):

  

 x

1 x

2

   

 x

1

 x

2

 

  sin

 sin

 x

1

  sin x

1

0

0

0

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 31

Unit 3. M-file Programming

Thus, the description in the state space can be expressed as:

1

2

 x

2

  sin x

1

  x

2

 

M-file: Then, we have to create a function containing such a description: function xdot=pendulum(t,x) alpha=0.5;gamma=1;beta=0; xdot(1,:)=x(2); xdot(2,:)=-alpha*x(2)-gamma*sin(x(1))+beta;

Calling ode23: Finally, we call ode23 from the command window:

>> Tinitial=0;Tfinal=10;init_cond=[0;1];

>> ode23(@pendulum,[Tinitial Tfinal],init_cond);

>>

Edit

Copy Figure (and, from Word, Paste)

4.3 Optimization

MATLAB has several functions for optimization.

Linear Programming: The function is linprog

. Linear programming is used in problems where the objective function and constraints are linear,

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 32

Unit 3. M-file Programming min x constraints : Ax

 b

A x

 b eq lb

  ub

Example 11.

Linear programming

(Magrab,05) Assume that two products A and B are produced along two production lines [mag, 05]. Each line has 200 hours. The product A makes a profit of 4€ per unit and needs 1h of the first line and 1.25h of the second line. The product B gives a profit of 5€ per unit and needs 1h of the first line and 0.75h of the second. There is a potential maximum demand in the market of 150 units of B. We want to know how many units of A and B maximize the benefit of the manufacturer. Defining x1 and x2 as the units of products A and B respectively, the objective function and constraints are as:

Minimize

Subject to: f g

1

(

: x

1

, x

1 x

2

)

 x

2 g

2 g

3

:

: 1 .

25 x

1 x

2

150

4 x

1

200

5 x

2

0 .

75 x

2

( x

1

, x

2

)

0

200

Thus, f

T 

4

5

1 .

1

25

0

1

0 .

75

1

 

 x

1 x

2



200

 

200

150

 f=[-4 -5];

A=[1 1;1.25 0.75;0 1]; b=[200 200 150]; lb=[0 0]; x=linprog(f,A,b,[],[],lb,[])

Optimization terminated. x =

50.0000

150.0000

Nonlinear programming: These are optimization problems where the criterion and / or constraints are nonlinear. In the case of unconstrained optimization, min x f ( x ) , the functions are fminunc

and fminsearch

. The first one uses derivative techniques

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 33

Unit 3. M-file Programming

Example: Consider the function f ( x )

1 .

625 x

4 

12 .

75 x

3 

31 .

375 x

2 

26 .

25 x

10 .

To plot it, since it is a polynomial, you can use the polyval

command,

>> coefs=[1.625 -12.75 31.375 -26.25 10];

>> x=linspace(0,4);

>> y=polyval(coefs,x);

>> plot(x,y)

10

8

6

4

2

0

-2

0 0.5

1 1.5

2 2.5

3 3.5

4

The function that contains the curve of which we are going to find the local minima is: function y=curve2(x) coefs=[1.625 -12.75 31.375 -26.25 10]; y=polyval(coefs,x);

Using fminsearch

:

>> fminsearch(@curve2,0.5) ans =

0.6425

>> fminsearch(@curve2,3) ans =

3.3853

Finding local maxima: It is enough to change the sign of the curve and use fminsearch

again.

Optimization in 2-variable functions: The command is again fminsearch

. For instance, function z=surface(u) x=u(1); y=u(2); z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...

- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...

- 1/3*exp(-(x+1).^2 - y.^2);

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 34

Unit 3. M-file Programming

>> fminsearch(@surface,[0 0]) ans =

0.2964 0.3202

>>

4.4 Timers

Timers are implemented by combining struct type variables and functions that call other functions.

Example: Edit a file trial.m

with the following commands: function trial

%we create a "timer" object t=timer('StartDelay',2,'Period',1,'TasksToExecute',2,'Executi onMode','fixedRate'); t.StartFcn = {@suma,'Initial: ',1,2};

%We begin by adding 1+2 t.StopFcn = {@suma, 'Final: ',3,4};

%We terminate by adding 3+4 t.TimerFcn = { @suma, 'running...',6,7};

%Meanwhile we add 6+7

%Start the timer start(t) function suma(obj,event,txt,arg_in1,arg_in2) result=arg_in1+arg_in2 event_type = event.Type; event_time = datestr(event.Data.time); msg = [txt,' ',event_type,' ',event_time]; disp(msg)

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 35

Unit 3. M-file Programming

The result is: result =

3

Initial: StartFcn 15-Mar-2010 18:03:24 result =

13 running... TimerFcn 15-Mar-2010 18:03:26 result =

13 running... TimerFcn 15-Mar-2010 18:03:27 result =

7

Final: StopFcn 15-Mar-2010 18:03:28

>>

4.5 Integration and derivation

In this section we use the function “humps” which is already defined in MATLAB. The file humps.m

contains the following function: f ( x )

( x

1

0 .

3 )

2 

0 .

01

( x

1

0 .

9 )

2 

0 .

04

6

To plot the function, type the following sentences:

>> x=linspace(-1,2);

>> y=humps(x);

>> plot(x,y),grid,xlabel('x'),ylabel('y'),title('Función "humps"')

Función "humps"

100

80

60

40

20

0

-20

-1 -0.5

0 0.5

x

1 1.5

2

The integral value I for function humps between -1 and 2 is I =26.34496047137833.

Integrate a function is equivalent to compute the area below such a function. MATLAB presents commands that numerically approximate the integral of functions.

Main functions are:

trapz

, cumtrapz

, quad

, quadl

, dblquad

, and triplequad

.

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 36

Unit 3. M-file Programming

Approximate integral by means trapezoid areas of equal base (trapz): It is possible to integrate the whole area I

  x

1 x

2 f ( x ) dx by means the sum of the areas of equal base trapezoids (Simpson rule). The function is trapz

. The result will be more accurate if the trapezoids base is small:

x x ( n +1) x ( n )

n -1 n n +1

t

.

T T

The shadowed area is x ( n )

 x ( n

1 )

T

2

>> x=linspace(-1,2,30);y=humps(x);area1=trapz(x,y),paso=x(2)-x(1), area1 =

26.2102 paso =

0.1034

>> x=linspace(-1,2);y=humps(x);area1=trapz(x,y),paso=x(2)-x(1), area1 =

26.3447 paso =

0.0303

Cummulative integral (cumtrapz): If you want to evaluate the integral as a function of x , I ( x )

  x

1 x f ( x ) dx , you can use cumtrapz

.

>> x=linspace(-1,2);y=humps(x);I=cumtrapz(x,y);

>> plot(x,y,x,I),grid,xlabel('x'),ylabel('y'),

>> title('Función "humps" y su integral acumulada')

Función "humps" y su integral acumulada

100

80

60

40

20

0

-20

-1 -0.5

0 0.5

x

1 1.5

2

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 37

Unit 3. M-file Programming

Quadrature integral (quad and quadl): Depending on the curve shape, these functions modify the base of each of the trapezoid areas in order to improve the results obtained with trapz

. Function quadl

( l comes from adaptive Lobato) is slightly better than quad. Both functions need a function with the curve description.

>> format long

>> quad(@humps,-1,2) ans =

26.34496050120123

>> quadl(@humps,-1,2) ans =

26.34496047137897

Integration and derivation of polynomials: Although a polynomial derivative is easy to compute, there exists the polyder

function.

Example: Given p ( x )

 x

3 

2 x

2 

3 x

4 , its derivative is dp ( x ) / dx

3 x

2 

4 x

3

>> p=[1 2 3 4];

>> dp=polyder(poli) dp =

3 4 3

There also exist the function polyint to integrate polynomials,

( 3 x

2 x 3 x 2

4 x

3 ) dx

3

4

3 x

 ct

3 2 corresponds to the integration constant.

. The second input argument of the function

>> polyint(dp) ans =

1 2 3 0

>> polyint(dp,4) ans =

1 2 3 4

Derivation: The function is diff

and it computes the progressive difference between samples, dy dx

 y

 x

 f ( x

  x )

 x

 f ( x )

It is recommended to use this function only in the cases the curve is smooth. If it is not de case (for instance in the case of discrete data), it is recommended to smooth the curve before using diff

.

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 38

Unit 3. M-file Programming

Symbolic integration and derivation: It is possible to use the function of the Symbolic

Toolbox. For more details, type

>>help symbolic

.

Before using a symbolic operation, you can declare the selected variables as symbolic objects:

>> syms x n

Symbolic integration: The function is int

. For instance, the integration of x n dx

 n x n

1

1

. The commands are: n x is

>> syms x n

>> f=x^n;

>> int(x^n) ans = x^(n+1)/(n+1)

Another example: To obtain the “humps” integral as a function of x:

>> syms x y

>> y = 1 / ((x-.3)^2 + .01) + 1 / ((x-.9)^2 + .04) - 6;

>> int(y,x) ans =

10*atan(10*x-3)+5*atan(5*x-9/2)-6*x and to plot it:

>> clear x z,

>> x=linspace(-1,2);z=10*atan(10*x-3)+5*atan(5*x-9/2)-6*x;

>> plot(x,y,x,I,x,z),grid,

100

80

60

40

20

0

-20

-1 -0.5

0 0.5

1 1.5

2

Integral in an interval: Consider again the humps example:

>> int(y,-1,2) ans =

10*atan(17)-18+5*atan(11/2)+10*atan(13)+5*atan(19/2)

>> 10*atan(17)-18+5*atan(11/2)+10*atan(13)+5*atan(19/2) ans =

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 39

Unit 3. M-file Programming

26.34496047137833

Symbolic derivation: The function is diff

but applied to symbolic objects:

>> syms x

>> diff(log(x)) ans =

1/x

4.6 Interpolation and regression. Polynomial fitting of curves

To interpolate is to estimate unknown intermediate values in a set of known values. It is an important operation in data analysis and curve fitting.

Interpolation in one dimension (interp1): it uses polynomial techniques. It fits a polynomial between each couple of points and it estimates the value in the desired interpolation point.

Example: Consider we have few points of a sinusoid:

>> x=linspace(0,2*pi,10);y=sin(x);figure(1),plot(x,y,'+',x,y)

1

0.8

0.6

0.4

0.2

0

-0.2

-0.4

-0.6

-0.8

-1

0 1 2 3 4 5 6 7

We want to know the curve value at point 0.5. To interpolate such a value we can use the interp1

function. There are several interpolation techniques available:

>> s=interp1(x,y,0.5,'linear') s =

0.4604

>> s=interp1(x,y,0.5,'cubic') s =

0.4976

>> s=interp1(x,y,0.5,'spline') s =

0.4820

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 40

Unit 3. M-file Programming

The exact value is sin(0.5)=0.4794. therefore, the ‘spline’ option is the one that gives the better result in this case.

Interpolation in two dimensions (interp2): It is like interp1 but now we interpolate in a plane.

Example: The script sea_bed.m

contain data from the sea bed depth measurements.

%sea_bed.m

%sea bed depth measurements x=0:0.5:4; %km y=0:0.5:6; %km z=[100 99 100 99 100 99 99 99 100;

100 99 99 99 100 99 100 99 99;

99 99 98 98 100 99 100 100 100;

100 98 97 97 99 100 100 100 99;

101 100 98 98 100 102 103 100 100;

102 103 101 100 102 106 104 101 100;

99 102 100 100 103 108 106 101 99;

97 99 100 100 102 105 103 101 100;

100 102 103 101 102 103 102 100 99;

100 102 103 102 101 101 100 99 99;

100 100 101 101 100 100 100 99 99;

100 100 100 100 100 99 99 99 99;

100 100 100 99 99 100 99 100 99]; figure(1),mesh(x,y,z), xlabel('x (km)'),ylabel('y (km)'),zlabel('Profundidad (m)')

108

106

104

102

100

98

96

6

4

4

3

2

2

1 y (km)

0 0 x (km)

If we want to interpolate the depth in the point (2.2,3.3), we can do:

>> interp2(x,y,z,2.2,3.3,'cubic') ans =

104.1861

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 41

Unit 3. M-file Programming

Regression line: Consider several points ( x , y ). We want to find the curve that best fits all of them. x -2 -1 0 1 2 3 4 5 6 7 8 y 1.94 -2.71 0.34 5.50 4.77 6.61 6.70 12.38 9.79 18.24 23.27

To plot them, simply create a script with the following commands: x=[-2,-1,0,1,2,3,4,5,6,7,8]; y=[1.94,-

2.71,0.34,5.50,4.77,6.61,6.70,12.38,9.79,18.24,23.27]; figure(1),plot(x,y,'o'),grid,xlabel('x'),ylabel('y')

Puntos y recta de regresión

25

25

20

20

15

15

10

10

5

5

0 0

-5

-2 0 2 4 6 8

-5

-2 0 2 4 6 8 x x

 ax

 b is equivalent to specify its slope a and its ordinate in origin To find the line y r b . Since there is no straight line that contains all the points, we have to look for a optimal straight line in the sense it minimises the sumo f the squared errors in the known points.

>> coefs=polyfit(x,y,1) coefs =

2.1317 1.4985

To plot the line y r

2 .

1317 x

1 .

4985 , use the polyval

function, yr=polyval(coefs,x); hold on,plot(x,yr,'r'),title('Puntos y recta de regresión'), hold off

It is also possible to type yr=coefs(1)*x+coefs(2)

.

Polynomial fitting: For the case of polynomials of order 2 or more, the procedure is the same:

%quadratic regression x=0:0.1:1; y=[-.447 1.978 3.28 6.16 7.08 7.34 7.66 9.56 9.48 9.3 11.2]; coefs1=polyfit(x,y,2); x1=linspace(0,1);y1=polyval(coefs1,x1); figure(2),plot(x,y,'or',x1,y1),grid,xlabel('x'),ylabel('y'),

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 42

Unit 3. M-file Programming title('Puntos y polinomio de orden 2')

%curve that fits all the points exactly n=length(x); coefs2=polyfit(x,y,n-1); x2=linspace(0,1);y2=polyval(coefs2,x1); figure(3),plot(x,y,'or',x2,y2),grid,xlabel('x'),ylabel('y'), title(['Puntos y polinomio de orden ',num2str(n-1)])

Puntos y polinomio de orden 2

Puntos y polinomio de orden 10

12

10

8

6

16

14

12

10

8

6

4

2

0

4

2

0

-2

0 0.2

0.4

0.6

0.8

1

-2

0 0.2

0.4

0.6

0.8

1 x x

>> coefs1 coefs1 =

-9.8108 20.1293 -0.0317

>> coefs2 coefs2 =

1.0e+006 *

Columns 1 through 7

-0.4644 2.2965 -4.8773 5.8233 -4.2948 2.0211

-0.6032

Columns 8 through 11

0.1090 -0.0106 0.0004 -0.0000

Pseudoinverse. Fitting of curves linear in the parameters (pinv function): The pseudoinverse matrix can be used to estimate linear in the parameters expressions such as y ( x )

 a

0

 a

1 e

0 x

.

3

 a

2 e

 x

0 .

8 ; where the unknown values are

 a

0

, a

1

, a

2

( 3 ,

5 , 2 ) . x=0:0.2:3; y=3-5*exp(-x/0.3)+2*exp(-x/0.8); figure(4),plot(x,y,'xk')

H=[ones(size(x')) -exp(-x'/0.3) exp(-x'/0.8)]; coefs=pinv(H)*y' pause, xrep=linspace(0,3);

Hrep=[ones(size(xrep')) -exp(-xrep'/0.3) exp(-xrep'/0.8)]; hold on,plot(xrep,Hrep*coefs) coefs =

3.0000

5.0000

2.0000

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 43

Unit 3. M-file Programming

3.5

3

2.5

2

1.5

1

0.5

0

0 0.5

1 1.5

2 2.5

3

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 44

Unit 3. M-file Programming

5. Signal Processing

MATLAB can import audio files (function wavread

) and can access the audio hardware to listen to them (function sound

).

Example 12. Finding the pitch frequency of a human voice

In a

*.wav

file we have recorded the sentence “el golpe de timón fue sobrecogedor” with the following options: sampling frequency 11025Hz, mono and 16bits.

Next we plot the signal, we estimate the spectral density by means the Barlett method

(with triangular window of M =512 samples) and we search for the fundamental pitch frequency (it happens to be 140Hz, a male voice).

[y,fs,bits]=wavread('frase'); fs,bits

%cut the sequence pot=fix(log2(length(y)));

N=2^pot; x=y(1:N); sound(x,fs,bits)

%spectral estimation

M=512;K=N/M;w=triang(M);

Sxx=zeros(1,M); for i=1:K

xi=x( (i-1)*M+1 : i*M )'.*w';

Xi=fft(xi);

Sxxi=(abs(Xi).^2)/M;

Sxx=Sxx+Sxxi; end

Sxx=Sxx/K;

%time plot t=0:1/fs:(N-1)/fs; subplot(211),plot(t,x),grid,xlabel('tiempo [s]'),ylabel('x')

%frequency plot f=linspace(0,fs/2,M/2); subplot(212),plot(f,10*log10(Sxx(1:M/2))),grid,ylabel('Sxx'), xlabel('frecuencia [Hz]'),text(3000,-50,'Bartlett, triangular, M=512')

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 45

Unit 3. M-file Programming

5.2 Fast Fourier Transform (FFT)

Consider a sequence of samples x [ n ], n = 0,…, N -1, in the time domain. We want to estimate the magnitude of its spectral density.

Fast Fourier Transform: Roughly speaking, to pass from the time domain to the frequency domain what we do is to apply the Fourier transform to the time samples. If

N is large this is unfeasible. Fortunately there exists one fast algorithm called FFT

( Fast Fourier Transform ) that can be used when the number of samples is a power of 2.

MATLAB implements the FFT.

Before applying the FFT we can do two things:

Truncate the original sequence (we take only the first 2 k

samples)

Complete the original sequence with a number of “0” such that the final length

N a power of 2 ( zero padding ).

Here we truncate the original sequence:

[y,fs,bits]=wavread('frase'); fs,bits

%sequence truncation pot=fix(log2(length(y)));

N=2^pot; x=y(1:N); sound(x,fs,bits)

Methods for spectral density estimation: Now we have several options to obtain spectra. We can take pieces of the original sequence, apply a window to them or not, compute the FFT of each piece, find the average among all pieces, use or not overlapping between windows, etc. All these strategies aim to improve the estimation

(computing load, improve the discrimination of the frequency peaks, improve the quality factor, smooth the estimate,…). Main methods are the following:

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 46

Unit 3. M-file Programming

Periodogram method: Consists of directly applying the expression:

2

S

ˆ x

( f )

1

,

N n

N 

1

0 x

  e

 j 2

 fn where S

ˆ x

( f ) is the so-called periodogram.

Bartlett method or periodogram average: Consists of Split the sequence x [ n ] of N samples in K segments of M samples each segment and average the K resulting periodograms:

Segment k : x k

   m

 kM

, k

0 ,..., K

1 , m

0 ,..., M

1

Periodogram of segment k : S

ˆ x k

( f )

1

M m

M 

1

0 x k

  e

 j 2

 fm

2

, k

0 ,..., K

1

Average of the periodograms of the K segments: S

ˆ x

( f )

1

K k

K 

1

0

S

ˆ x k

( f )

Welch method: This method is also known as average of modified periodograms. It is an extension of the Barlett method with two differences: we introduce overlapping D between segments and these are windowed with w [ n ]. the procedure is the following:

Split the N samples sequence x [ n ] into K segments of M samples each one and introduce an overlap of D samples between segments:

Segment k : x k

   m

 kM

D

, k

0 ,..., K

1 , m

0 ,..., M

1 (if

D = 0.5

M the overlap is 50%, if D = 0.1

M it is 10%)

The K segments are windowed with w [ n ] and the periodograms are computed.

The periodograms are normalized in order to take into account the window effect:

Periodogram of segment k : S

ˆ x k

( f )

1

MU k

0 ,..., K

1 , where U

1

M m

M 

1

0 w

2

.

M 

1 m

0 x k

    e

 j 2

 fm

2

,

Finally the K resulting periodograms are averaged: Average of the periodograms of the K segments: S

ˆ x

( f )

1

K k

K 

1

0

S

ˆ x k

( f )

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 47

Unit 3. M-file Programming

Blackman-Tukey method or peridogram smoothing: We take the N samples of x [ n ] and compute their correlation R xx

[ k ]. The samples of R xx

[ k ] farthest from the origin are not considered since they have been obtained from a few samples of x [ n ]. Therefore, the correlation is windowed with a M length window centered at the origin. To compute the spectral density we apply the FFT to the windowed correlation R xx,v

[ m ].

MERIT. MATLAB. Fundamentals and/or Applications. Course 1314b 48

Download