0% found this document useful (0 votes)
95 views

Simple Programming in MATLAB PDF

The document describes how to plot a function in MATLAB using three steps: 1) Create x-values between 0 and 1, 2) Compute y-values using the function, and 3) Plot the points (x,y). It provides examples of creating x-values manually or using linspace, computing y-values using vector operations, and plotting the graph. It also discusses creating MATLAB script files to automate plotting and defining custom functions in separate files to reuse calculations.

Uploaded by

KT J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

Simple Programming in MATLAB PDF

The document describes how to plot a function in MATLAB using three steps: 1) Create x-values between 0 and 1, 2) Compute y-values using the function, and 3) Plot the points (x,y). It provides examples of creating x-values manually or using linspace, computing y-values using vector operations, and plotting the graph. It also discusses creating MATLAB script files to automate plotting and defining custom functions in separate files to reuse calculations.

Uploaded by

KT J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Simple Programming in MATLAB

We will plot the graph of the function


1.5x
y = f (x) = e sin(8⇡x), 0x1
Plotting a graph using MATLAB involves three steps:
• Create points 0 = x1 < x2 < · · · < xn = 1.
• Compute yi = f (xi ), i = 1, 2, · · · , n.
• Draw a polygonal line that connects the points (x1 , y1 ), (x2 , y2 ), · · · , (xn , yn ).

Step 1: Create x-values: We first create a vector x = (x1 , x2 , · · · , xn ) for n = 5. It


could be done in several ways:
(a) We can create the vector manually:
>> x = [0 .25 .5 .75 1] <ret>
x =
0 0.2500 0.5000 0.7500 1.0000
Here x(1) = 0, x(2) = .25, x(3) = .5, x(4) = .75 and x(5) = 1.
(b) We may also use the “do - loop”.
>> n = 5; (ret)
>> h = 1/(n-1); (ret)
>> for k=1:n (shift-ret)
x(k)=(k-1)*h; (shift-ret)
end (shift-ret)
>> x (ret)
x =
0 0.2500 0.5000 0.7500 1.0000
(c) We may also use MATLAB’s linspace command:
>> x = linspace(0,1,5) (ret)
x =
0 0.2500 0.5000 0.7500 1.0000
Thus we have created a row vector x of size n (n = 5 in this case).

Step 2: Compute y-values:


>> y = exp(-1.5*x) .* sin(8*pi*x)
y is a vector, where yi = e 1.5xi sin(8⇡xi ). This step requires some explanation. Here x
= [x(1) x(2) · · · x(5)] is a row-vector, i.e., it is a matrix of size 1 ⇥ 5.
• -1.5*x is a vector [-1.5*x(1), -1.5x(2), · · · , -1.5x(5)].
• pi is the usual ⇡ in MATLAB.
• exp(-1.5x) is the vector [exp(-1.5*x(1)),exp(-1.5*x(2)),· · · ,exp(-1.5*x(5))]
• sin(8*pi*x) is a vector [sin(8*pi*x(1)), sin(8*pi*x(2)), · · · , sin(8*pi*x(5))]
1
2

• The operation “ .*” is the vector multiplication operation of MATLAB, which is


“component-wise” multiplication. If a = (a1 , a2 , · · · , an ) and b = (b1 , b2 , · · · , bn ).
Then a .* b is the vector (a1 b1 , a2 b2 , · · · , an bn ). Other standard vector operations
are similar, e.g., a./b is the vector
(a1 /b1 , a2 /b2 , · · · , an /bn ).
• Based on the discussion, it is clear that y is the vector (y1 , y2 , · · · , y5 ) where yi =
f (xi ).

Step 3: Plotting the points ( x(i), y(i) ):


>> plot(x,y)
−16
x 10
0

−0.5

−1

−1.5

−2

−2.5

−3
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

The graph is disappointing. The reason for this strange graph is that we we took a low
value of n. We can take a higher value of n, and repeat all the commands, which will
require a lot of typing. To avoid such situations, we will create and execute a MATLAB
script file, in the next section.

Exercise: Plot the graph of y = sin(x) using 11 equally spaced points in the interval
[0, 2⇡], i.e., with xi = (i 1)h, i = 1, 2, · · · , 11, where h = 2⇡/10.
3

Writing MATLAB scripts

A MATLAB script is an ASCII file, created by the user, which contains a sequence of
MATLAB commands. This file must be saved with an extention “.m”. They are also re-
ferred to as M-files. By typing the name of the script file (without the ‘.m’ extension) at the
command-prompt (>>), we execute the script, i.e., execute all the commands sequentially.

Current Directory: The files created in MATLAB are usually stored in the current
directory (folder) of MATLAB. The current directory is displayed in a window just above
the command window. The default current directory of MATLAB may not be the best
place to save a file for proper organization. For example, we may create a new directory,
called “MatlabTutorial”, make MatlabTutorial as the current directory, and save files in
that directory. One can change the current directory to MatlabTutorial by navigating
through the browse button, located next to the current directory display. A script file may
be executed if it is in the current directory (by changing the MATLAB path, one can access
also other directories).

Creating script file: Select File - New - M-File from the File menu of MATLAB window.
An edit window will appear. Type the appropriate MATLAB commands in the file. In our
case, we type the following:

% Script 1; Script to plot a function


n=10;
x=linspace(0,1,n);
y=exp(-1.5*x).*sin(8*pi*x);
plot(x,y)

Now save this script file by selecting File - Save As... frome the File menu of the
edit window. For example, save it as “sc1.m”. Note that we have used n=10, and have
suppressed the output of each command by putting a ‘;’ at the end of the commands. To
execute this script file, we type at the command prompt

>> sc1 (ret)

We get the graph


4

0.6

0.4

0.2

−0.2

−0.4

−0.6

−0.8
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

The graph is still not good. We have to increase the value of n. If you have closed the
edit window, open the file sc1.m by selecting File - Open... and the file sc1.m. Change
n=100, save the file, and execute again. We get the following graph.
1

0.8

0.6

0.4

0.2

−0.2

−0.4

−0.6

−0.8
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

This looks realistic.


If we want to plot the graph of a di↵erent function, we can do that by editing the same
script file.

Exercise: Write a MATLAB script to plot the graph of the function y = sin(x) x , 20 
x  20. Experiment with the value of n (# of x-values) to get a realistic graph.
5

Creating Function files

A function file is just like a script file, but it has well-defined input and output variables.
It is also an M-File. These functions can be used in other scripts. For example, we used
the function
f (x) = e 1.5x sin(8⇡x)
in the script sc1.m, and typed it explicitly. We can define this function in a function file
as follows: First open an edit window and then type
function y = func1(x);
y = exp(-1.5*x) .* sin(8*pi*x);
Save this small file as ‘func1.m’ (use the same name as the name of the function while
saving). Note that the first line of this function file is the function definition line, which
clearly indicates the name of the function and the input/output variables. In this function,
x is the input variable which could be either a scalar or vector. The output variable is y;
it is scalar if x is scalar, and it is a vector if x is a vector. The size of y is same as the size
of x.
The function func1.m can be used in the script sc1.m by slightly changing the script as
follows:
% Script sc2.m; Script to plot a function
% We plot a function in the interval [a,b]
a = 0;
b = 1;
n=100;
x=linspace(a,b,n);
y=func1(x);
plot(x,y)
Save the script as sc2.m. Note that we have used y=func1(x);. Make sure that func1.m
and sc2.m are both in the current directory. Also note that we can assign other values to
the variables a and b (other that 0 and 1 respectively).
In this particular case, we really did not need to define the function func1.m, as it was
a simple function. But functions, used in MATLAB, can be complicated and it is useful
to define functions separately.
6

Flow-control: Loops and branches

MATLAB has its own flow-control structures, e.g., (a) the for-loop, (b) the while-loop,
(c) the if-statement, (d) the if-elseif-else statement, and others.

for-loop: A for-loop is used to repeat a command or a group of commands for a fixed


number of times.
Example:
% Print the values of sin(x) for
% x= 0, 0.1, 0.2, ....... , 0.9, 1.0
%
for k=1:11
x=(k-1)*0.1;
y=sin(x);
fprintf(’sin(%3.1f) = %7.5f \n’,x,y)
end
The variable k is the counter. Initially, k is assigned the value 1, and all the statements
between the for and end statements are executed. The value of the counter is increased
by 1 and the same statements are executed again. The process is repeated till k=11
The fprintf(.......) writes the formatted data. Type help fprintf at the com-
mand prompt for more info.
Th counter k could also be increased (or decreased) by a fixed value: for k=m:i:n
increases the counter k by i each time. In the following example,
for k=100:-2:0
x = 1/sqrt(k);
end
the counter k takes values 100, 98, 96, ...., 0. Type help for at the command
prompt for more info.

while-loop: A while-loop is used to execute a command or a group of commands for


indefinitely until the condition specified after the while is no longer true.
Example: Find all the powers of 2 below 100
% v = 1; num = 1; i = 1;
% while ( num < 100 )
num = 2^(i);
v = [v ; num];
i = i + 1;
end;
7

if-elseif-else statement: This construction provides logical branching of computations.


Example:
1 = 6; j = 21;
% if (i > 5)
k = 1;
elseif ( i > 1 ) & (j == 20)
k = 5*i+j ;
else
k = 1;
end

Exercise: For your computer, find the integer i and the real number u = 2 i such that
1 + u 6> 1 (weird – isn’t it?)
8

Example: Taylor Polynomials of ex :


We will write a function that computes the nth -degree Taylor polynomial of the function
f (x) = ex . The nth degree Taylor polynomial of f (x) = ex is
n
X xk x2 x3 xn
=1+x+ + + ··· +
k! 2! 3! n!
k=0

The function is defined as follows:


function y = TaylPol(x,n);
l = size(x);
y = ones(l);
term = ones(l);
for k=1:n
term = (term.*x)/k;
y = y + term;
end
Some comments of this function:
• TaylPol is a function of two variables, x and n. Here n is the degree of the Taylor
polynomial. y is the value of the Taylor polynomial at x; x could be a scalar or a
vector and y is a vector of same length.
• The command size(x) gives the size of x when x is considered as a matrix. In this
case, if x is a row-vector with 10 components, then size(x) = [ 1 10]. If x is a
scalar (a row-vector with one component), then size(x) = [1 1].
• The command ones(l) is a row vector of size l whose components are 1.
We now write a script which plots ex and its Taylor polynomials of degree 1, 3, and 5
for 0  x  4.
% Script sc3.m
% Plot exp(x) and its Taylor polynomials of
% degree 1, 3, and 5 for 0 <= x <= 4
n=400;
x=linspace(0,4,n);
y1=exp(x);
y2 = TaylPol(x,1);
y3 = TaylPol(x,3);
y4 = TaylPol(x,5);
plot(x,y1,’k-’,x,y2,’k--’,x,y3,’k-.’,x,y4,’k:’)
Comments:
• x is a vector of length 400 (note that size(x) = [1 400]). The components are
uniformly distributed values of x between 0 and 400 (including 0 and 400).
9

• y1 is the row-vector of values of ex , where x is the row-vector of length 400. y2,


y3 and y4 are row-vectors of values of the Taylor polynomials of degree 1, 3, and 4
respectively.
• The plot command plots four plots on the same graph. It first plots (x,y1) with
’k-’ option where k represents black color, and - represents solid line. It then
plots (x,y2) with ’k--’ option, i.e., black dashed line. The option ’k-.’ means
black dash-dot line, and ’k:’ means black dotted line.
The script sc3.m is then executed by typing
>> sc3
to get
60

50

40

30

20

10

0
0 0.5 1 1.5 2 2.5 3 3.5 4

Example: Values of sin x via its Maclaurin series:


We now present the last function of this section which evaluates sin x via its Maclaurin
series;
X1
x2k 1
sin x = ( 1)k+1
(2k 1)!
k=1
This series converges for every value of x. We will find sin x, for a given x, by “computing
the infinite series” in the following sense: We will compute the partial sum
Xn
x2k 1
Sn = ( 1)k+1 ,
(2k 1)!
k=1
for large enough n, such that
|Sn+1 Sn | is small.
10

Also the following observation will be useful in writing a MATLAB function for for this
procedure. The (k 1)th term of the infinite series is
x2k 3
ak 1 = ( 1)k .
(2k 3)!
And thus, thus the k th term can be written as

k+1 x2k 1 x2
ak = ( 1) = ak 1 ( 1)
(2k 1)! (2k 1)(2k 2)
We are now ready to write the function.
function y = sinmac(x)
% x could be a vector
ep = 10 ^ (-14);
l=length(x);
for k=1:l
sl = 0;
sn = x(k);
term = x(k);
con = 1;
pm = 1;
while (abs(sn-sl)>ep)
sl = sn;
con = con+2;
pm = -pm;
term = (term.*(x(k) ^ 2))/(con*(con-1));
sn = sn + term*pm;
end
y(k) = sn;
end
We use the following script to use this function.
x = [.5 pi/4 1.2];
sinmac(x)
The output will be
ans =
0.47942553860420 0.70710678118655 0.93203908596723
11

We can also use the script sc2.m with slight modification.


% Script sc2.m; Script to plot a function
% We plot a function in the interval [a,b]
a = 0;
b = 2*pi;
n=500;
x=linspace(a,b,n);
y=sinmac(x);
plot(x,y)
We get the graph
1

0.8

0.6

0.4

0.2

−0.2

−0.4

−0.6

−0.8

−1
0 1 2 3 4 5 6 7

Caution: We will later see certain problems with this function.

You might also like