15
Matlab Tutorial Session 2 Beginning Simple Programming in Matlab (Expected time: 1.5 hours to 2 hours) In session 1, everything was done directly at the command prompt. In this tutorial, the following topics are covered: 1. Using Matlab editor to write simple programs and running these programs. 2. FOR and WHILE loops. 3. Evaluating conditions IF-ELSE and related constructs. 4. Absence of GOTO-type branching and how to program without it. 5. More on workspace management and saving the results to a file. 6. Making simple plots. This tutorial is intended to provide enough Matlab knowledge to do some useful things. Short Review of Session 1 In Matlab, all variables are matrices. A point missed last time was that variable names distinguish between lowercase and uppercase characters. Thus a is not same as A. Variables are defined / altered spontaneously (as the context occurs) and they reside in the workspace. Matrices are defined using square braces + comma or space (for elements on same row) + semicolon or return key (for separating rows), e.g. >> A=[1,2,3;4,5,6] A = 1 2 3 4 5 6 Matrices can also be defined using built-in functions such as ones, eye, rand etc. Matrix elements are accessed using round brackets, e.g. >> A(2,3) ans = 6

Matlab Session 2

Embed Size (px)

DESCRIPTION

Matlab_Session_2.pdf

Citation preview

Page 1: Matlab Session 2

Matlab Tutorial Session 2

Beginning Simple Programming in Matlab (Expected time: 1.5 hours to 2 hours)

In session 1, everything was done directly at the command prompt. In this tutorial, the

following topics are covered:

1. Using Matlab editor to write simple programs and running these programs.

2. FOR and WHILE loops.

3. Evaluating conditions – IF-ELSE and related constructs.

4. Absence of GOTO-type branching and how to program without it.

5. More on workspace management and saving the results to a file.

6. Making simple plots.

This tutorial is intended to provide enough Matlab knowledge to do some useful things.

Short Review of Session 1

In Matlab, all variables are matrices. A point missed last time was that variable

names distinguish between lowercase and uppercase characters. Thus a is not

same as A.

Variables are defined / altered spontaneously (as the context occurs) and they

reside in the workspace.

Matrices are defined using square braces + comma or space (for elements on same

row) + semicolon or return key (for separating rows), e.g.

>> A=[1,2,3;4,5,6]

A =

1 2 3

4 5 6

Matrices can also be defined using built-in functions such as ones, eye, rand etc.

Matrix elements are accessed using round brackets, e.g.

>> A(2,3)

ans =

6

Page 2: Matlab Session 2

The colon operator defines a vector of equally-spaced numbers, e.g.

>> 1.2 : 0.1 : 1.8

ans =

1.200 1.300 1.400 1.500 1.600 1.700 1.800

>> A(1,:)

ans =

1 2 3

There are two types of operations – matrix operations and array operations. Array

operators begin with a dot ( . ). Examples are

>> A'*A % Note: A’ represents transpose of matrix A

ans =

17 22 27

22 29 36

27 36 45

>> A.*A

ans =

1 4 9

16 25 36

Mathematical functions such as sin, cos, sqrt, etc. all act on matrices, e.g.,

>> sin( A*pi/6 )

ans =

0.5000 0.8660 1.0000

0.8660 0.5000 0.0000

Many built-in matrix analysis functions such as eig, lu, rank, expm, etc. are

available, e.g.

>> [V,D]=eig( A'*A )

V =

-0.4082 -0.8060 0.4287

0.8165 -0.1124 0.5663

-0.4082 0.5812 0.7039

D =

-0.0000 0 0

Page 3: Matlab Session 2

0 0.5973 0

0 0 90.4027

Using Matlab Editor

Matlab editor is started by giving edit command at command prompt

Edit command given at

Command prompt

This is the

Matlab EditorLine numbers for program

Edit command given at

Command prompt

This is the

Matlab EditorLine numbers for program

The working of the editor is discussed below. An example is taken all along for

illustration.

1. The picture on next page shows the written program. Explanation is as follows:

a. All lines end with a semicolon except lines 15 and 18, because we want to

see the output on screen of only these two statements when program is

run. The output of other statements is suppressed by ending them with a

semicolon.

b. Matlab editor shows comments (which are indicated by the % sign) in

green, statements in black, keywords such as for, end in blue, strings in

red. (Keywords and strings will be encountered in this tutorial)

Page 4: Matlab Session 2

c. The program is a simple sequence of statements that could be otherwise

written directly at the command prompt. There are no formal beginning or

end indicators for the program.

2. Programs are written in the editor and saved as M-files, i.e. files with extension

“.m”, e.g. the above program is saved as newtdd.m using File→Save.

Note: The above program is available in the appendix at end of this tutorial so that it

can be cut and pasted directly in the editor to save time.

3. The default path where files are saved is C:\Matlab6p1\work. Files can be saved

in any other folder also. The next point explains an important note in this regard.

4. Programs are run by typing the name of the M-file at command prompt (the

extension “.m” is not required while calling the program). E.g. the program

above will be run by writing newtdd at the matlab command prompt. To run a

program like this, the path should be correct, i.e. matlab current path should be

same as the path where file is saved. To check / change matlab path the cd

command can be used, and to see the directory, dir command is used. E.g.,

Page 5: Matlab Session 2

>> cd

C:\MATLAB6p1\work

>> cd e:\folderA

>> dir

. .. subfolder1 subfolder2 programA.for

>> cd c:\matlab6p1\work

>> dir

. .. newtdd.m

5. Now the newtdd program is executed. The result is as follows

>> newtdd

x2 =

1.4000

fx2 =

2.2400

6. If the program was stored in another directory, such as c:\myprogs, then we have

to cd to that directory and then run the program. It is useful to check using dir

command whether the program is visible in the current directory or not before

trying to execute it.

7. Another possibility is to use the addpath command to add a specific folder to the

matlab path list. Matlab maintains a path list, which is just a collection of folder

names where matlab will search for a command / program. When a command is

given at the command prompt (e.g. >> newtdd), first matlab checks if it is a M-

file in the current directory. If not found, it checks if it is a built-in command. If

again not found, it checks all the folders in the path list sequentially to find that

M-file. Finally if the file is not found anywhere, it gives an error. (If the name of

a M-file in current directory is same as the name of a built in matlab command,

then that M-file will be executed instead of the built in command). Path can be

seen using the command path.

>> path

MATLABPATH

/opt/matlab/toolbox/matlab/general

/opt/matlab/toolbox/matlab/ops

/opt/matlab/toolbox/matlab/lang

/opt/matlab/toolbox/matlab/elmat

/opt/matlab/toolbox/matlab/elfun

... ... ...

Page 6: Matlab Session 2

>> addpath C:\folderA

>> path

MATLABPATH

C:\folderA

/opt/matlab/toolbox/matlab/general

/opt/matlab/toolbox/matlab/ops

/opt/matlab/toolbox/matlab/lang

/opt/matlab/toolbox/matlab/elmat ...

FOR Loop

The for loop is simply constructed using the colon operator. An example is given below

x=1;

for i=1:100

x=x*i;

end

The above statements compute factorial of 100. Real numbers can also be used, e.g.,

s=0;

for f = 0 : 0.1 : 10

s = s + f;

end

The above set of statements computes 0.103.02.01.00 s .

1. for loop is always ended by an end.

2. In matlab editor, the keywords for and end appear in blue color.

Conditions and Boolean Operations

There is no special boolean (fortran LOGICAL) variable type in matlab. Integer with value

0 is considered as FALSE and any non-zero integer represents TRUE (including negative

integers). Generally, built-in boolean expressions return 1 for TRUE. Logical operators

are:

Relational operators

Equal ==

Not equal ~=

Less than <

Greater than >

Less than or equal <=

Greater than or equal >=

Logical operators

Logical AND & and

Logical OR | or

and(a,b)

is equivalent to a & b.

Page 7: Matlab Session 2

Logical NOT ~ not

Logical EXCLUSIVE OR xor

Multiple logical operations

any - True if any element of vector is nonzero

all - True if all elements of vector are nonzero

Examples:

>> 5>3

ans =

1

>> 5<3

ans =

0

>> 4==4 % note: double == is for logical testing

% single = refers to assignment operation, like a=5

ans =

1

>> (3==3) & (4==4) % logical AND

ans =

1

>> and( (10>=5) , (10=<7) )

ans =

0

>> (10>5)|(10<7) % logical OR - on keyboard, SHIFT+\

ans =

1

>> ~(3>5) % logical NOT

ans =

1

Page 8: Matlab Session 2

IF ELSE Statement

The IF statement is as follows

if (condition)

statements for true condition

else

statements for false condition

end

As explained above, there is no special Boolean type, therefore „condition‟ is an

integer, 0 for false and nonzero for true.

There is no “then” keyword. The statement just following the if part is the “then”

part.

As in case of for loop, it is always ended by an end. The keywords if, else and

end appear in blue color in the editor.

Examples:

if (1)

a=2;

else

a=3;

end

>> a

a =

2

x=0.5;

y=x^2; % y is x raised to power 2

if ( y >= x )

disp('x was greater than or equal to 1');

else

disp('x was less than 1');

end

output:

x was less than 1

Note: disp(‘string’) command is used to output a string

The if construct can be expanded to more complex decision making by elseif

if (angle >= 0) & (angle < 90)

quadrant=1;

elseif (angle >=90) & (angle < 180)

quadrant=2;

elseif (angle >= 180) & (angle < 270)

Page 9: Matlab Session 2

quadrant=3;

elseif (angle >= 270) & (angle < 360)

quadrant=4;

else

disp('This is not a valid angle in degrees');

end

Note: There is no gap between else and if in elseif. It is a keyword on its own.

WHILE Loop

While loop is the only construct available in matlab for conditional looping.

There is no “goto”.

The syntax is

while (condition)

statements within the loop

end

Statements within the While loop may not execute at all if the condition is false at

the beginning.

As soon as condition becomes false, the loop ends. E.g. the following loop will

execute exactly 9 times

i=1;

while (i<10)

x(i)=i*i;

i=i+1;

end

output:

>> x

x =

1 4 9 16 25 36 49 64 81

While loop provided in matlab is sufficient for performing any type of conditional

looping. But some experience is required how to accordingly write the program.

Some example programs given at end may provide some idea.

Workspace and Simple File Management

As all variables reside on the workspace, sometimes the whole memory might get

unnecessarily consumed. This might occur in programs that require excessive storage.

When memory demand is more than RAM size, hard disk is used as a swap memory, but

this considerably reduces the speed of program executions. Such situation is

Page 10: Matlab Session 2

symptomized by a continuous glowing of hard disk indicator LED while the program is

executing. Following commands are provided for workspace management

1. Variables present in the workspace can be viewed using who and whos

commands, or on the workspace browser in the left hand side pane adjacent to

command window (View→Workspace).

2. Unnecessary variables can be cleared from workspace using the clear command;

clear all command clears all the variables from workspace.

3. A variable / all variables can be saved to a file using save command. Similarly,

load command retrieves from a specified file any previously saved variables.

These files are in matlab “.mat” format and are called MAT-files.

4. Matlab also supports text files with delimiters (some separating symbol such as

comma, tab or space) using the commands dlmread and dlmwrite.

5. Excel files can only be read using xlsread command.

6. More details can be obtained by typing help <commandname> at the command

prompt (e.g. help dlmread). More complex file input / output is subject of the

next tutorial.

>> who % variables a b c were created beforehand

Your variables are:

a b c

>> whos

Name Size Bytes Class

a 2x3 48 double array

b 1x6 12 char array

c 1x1 8 double array

Grand total is 13 elements using 68 bytes

>> clear a % syntax is: clear <variable1> <variable2> ...

% e.g. clear a b c

% Note that there is no comma or semicolon

>> who

Your variables are:

b c

>> clear all % clears the whole workspace

>> who

>> % empty output as all variables were cleared

>> a=[1 2 3; 4 5 6; 7 8 9];

>> b='string';

>> who

Page 11: Matlab Session 2

Your variables are:

a b

>> save varA.mat a

% syntax: save filename variable1 variable2 ...

% again there is no comma or semicolon

% filename is without any quotation marks

% default extension is .mat

>> save varAB.mat

% this saves all workspace to the specified filename

>> clear all % No variables left in workspace

>> load varAB % Now loading the previously saved variables

>> who

Your variables are:

a b

% It is possible to load only few variables from a whole .mat

% file by using the syntax:

% load filename variable1 variable2 ...

% the variable names must be correctly specified as the

% original names at time of saving

>> dlmwrite('varA.txt',a,' ')

% the delimiter is specified here as single space

% Limitation is that this command can save only

% one variable in a file. So each variable has to

% be saved in an individual file

the file varA.txt looks as follows (open in notepad etc.)

1 2 3

4 5 6

7 8 9

Later in this tutorial is an example of how to create a file that can be read as a datafile in

Tecplot.

Making Simple Plots

The matlab command figure creates a figure window. A figure window has its own

menubar and toolbar that provides facilities like saving the figure, zoom, rotation, adding

arrows, lines and text, changing line colors, thickness etc. Many figures can be created

simultaneously and each figure has its own figure window. Therefore matlab provides a

number to each figure. This number is called a handle. A handle is an important concept

of matlab which will be discussed in a later tutorial.

Page 12: Matlab Session 2

To create a new figure: >> fno=figure; This creates a new figure window

and returns a figure number in the variable fno.

The programmer can assign a number of his choice to the figure by creating the

figure with the command figure(<number>), e.g., >> figure(100);

There is a “current figure” to which all plotting commands are applied. To make

a particular figure as current figure, the figure command is given with an existing

figure number. E.g. if there are two figures, 1 and 100, existing on the screen at

same time, figure 1 can be made the current figure by issuing the command >>figure(1);

Thus, in summary, figure command creates a new figure or makes an existing

figure the current figure. Each figure is associated with a handle number.

In any figure, a plot is generated using plot command. Plot command can be issued with

multiple syntax, each having different effect, as discussed below:

1. plot(Y) : plots the vector Y as iiy vs. .

2. plot(X,Y) : plots the vector Y against X as ixiy vs. . The sizes of vectors Y

and X must agree.

3. plot(X,Y,style) or plot(Y,style) adds a style formatting to the simple plot

command. style is a string where each character sets an attribute. This string is

made from one element from any or all the following 3 columns:

y yellow . point - solid

m magenta o circle : dotted

c cyan x x-mark -. dashdot

r red + plus -- dashed

g green * star

b blue s square

w white d diamond

k black v triangle (down)

^ triangle (up)

< triangle (left)

> triangle (right)

p pentagram

h hexagram

Examples: Please see on next page.

Note: hold on command had been used in the examples on next page. In general when a

two plot commands are given one after the other, the new plot command erases the

previous plot and creates a new plot. This is called the hold off mode. But by specifying

hold on, the new plot command adds its contents on the previous plot. The axis are

automatically adjusted such that both the plots can fit together.

Page 13: Matlab Session 2

Title and axis labels can be using the commands title(„name‟), xlabel(„name‟),

ylabel(„name‟). The titles and labels are applied to the current figure. Legend can also

be added, but this requires some details, which will have to be discussed in a future

tutorial.

The command close(<fno>) closes the figure window with handle fno. The command

close all closes all the figures.

>> y=(1:10).*(1:10);

>> figure(1)

>> plot(y)

>>

>> t=0 : 0.1 : 2*pi ;

>> x=sin(t);

>> y=cos(t);

>> figure(2);

>> plot(x,y)

Page 14: Matlab Session 2

>> t=0:0.01:1;

>> a=t.^2;

>> b=t.^3;

>> c=t.^4;

>> figure(3);

>> plot(a,'r:');

>> hold on;

>> plot(b,'k--');

>> hold on;

>> plot(c,'b');

>> title('Powers plot')

>> xlabel('x');

>> ylabel('Powers of

x');

Example Programs

Fourth order Runge-Kutta method for solution of an initial value problem yxfy

, .

There are multiple variables.

clear all; close all; % Empty the workspace and close all

open windows

% In this example, we are solving the problem : N'th

derivative of y = -K*(x^2)

% Converting into N first order derivatives

% Let

% y_N'(x) = -K*(x^2)

% y_N-1'(x) = y_N(x)

% y_N-2'(x) = y_N-1(x)

% ....

% y_1'(x)= y_2(x)

% y(x) = y_1(x)

%

% So the final solution will be in y(1)

% Therefore [y_1'(x) y_2'(x) ... y_N'(x)] = f(x,y)

% = [y_2(x) y_3(x) ... y_N(x) -K*(x^2)]

% = AY + bx where Y is the vector [y_1 y_2 ... y_N]

N=5; K=10;

% Initial values are given as:

% y(0)=0; y'(0)=1; y''(0)=1; ...; y(nth derivative at 0)=1

% Finally we have to find y(4)

X1=0; X2=4;

h=0.1;

x=X1:h:X2; % x-axis point where y will be calculated

Page 15: Matlab Session 2

niter=length(x); % number of iterations

y=zeros(niter,N); % initializing y as a two-dimensional array,

% each row has [y_1(x) y_2(x) ... y_N(x)

% each iteration has particular x

y(1,1:N)=[0 ones(1,N-1)]; % Setting the initial conditions

for i=2:niter

yA=y(i-1,:);

xA=x(i-1);

fA=[yA(2:N) -K*(xA^2)];

% The above statement is because

% [y_1'(x) y_2'(x) ... y_N'(x)] = f(x,y)

% = [y_2(x) y_3(x) ... y_N(x) -K*(x^2)]

k1=h*fA;

yB=y(i-1,:)+k1/2;

xB=x(i-1)+h/2;

fB=[yB(2:N) -K*(xB^2)];

k2=h*fB;

yC=y(i-1,:)+k2/2;

xC=x(i-1)+h/2;

fC=[yC(2:N) -K*(xC^2)];

k3=h*fC;

yD=y(i-1,:)+k3;

xD=x(i-1)+h;

fD=[yD(2:N) -K*(xD^2)];

k4=h*fD;

y(i,1:N)=y(i-1,1:N) + k1/6 + k2/3 + k3/3 + k4/6;

end

yans=y(:,1); % because answer is in y_1

figure(1);

plot(x,yans);

More example programs will be the next tutorial.